0% found this document useful (0 votes)
101 views

PHP and MySQL Handbook

The document provides information about PHP and MySQL. It defines PHP as a server-side scripting language used to build dynamic websites. It can be used to create, read, update and delete data from MySQL databases. The document also discusses PHP variables, data types, outputting variables, and variable scope. It provides examples of PHP syntax including comments, variables, and functions.

Uploaded by

Balex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

PHP and MySQL Handbook

The document provides information about PHP and MySQL. It defines PHP as a server-side scripting language used to build dynamic websites. It can be used to create, read, update and delete data from MySQL databases. The document also discusses PHP variables, data types, outputting variables, and variable scope. It provides examples of PHP syntax including comments, variables, and functions.

Uploaded by

Balex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

MAKERERE INSTITUTE OF TECHNOLOGY

DEPARTMENT OF INFORMATION
TECHNOLOGY

SERVER SCRIPTING LANGUAGE

[PHP AND MySQL]

STUDENT’S COPY

STUDENT NAME: SSEKYANZI ISAAC


COURSE: DIPLOMA IN SOFTWARE ENGINEERING

REG NO: DSE/AUG19/W/695

BAZIGU ALEX || 0778056780 || 0704923822 1


PHP AND MYSQL

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.

PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

PHP 7 is the latest stable release.

PHP code is executed on the server.

What You Should Already Know


Before you continue you should have a basic understanding of the following:

 HTML
 CSS
 JavaScript

If you want to study these subjects first, find the tutorials on our Home page.

Definition of PHP
PHP is an acronym for "PHP: Hypertext Preprocessor"

PHP is a widely-used, open source scripting language

PHP scripts are executed on the server

PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!

It is deep enough to run the largest social network (Facebook)!

It is also easy enough to be a beginner's first server side language

What is a PHP File?


PHP files can contain text, HTML, CSS, JavaScript, and PHP code

PHP code is executed on the server, and the result is returned to the browser as plain HTML
BAZIGU ALEX || 0778056780 || 0704923822 2
PHP files have extension ".php"

What Can PHP Do?


PHP can generate dynamic page content

PHP can create, open, read, write, delete, and close files on the server

PHP can collect form data

PHP can send and receive cookies

PHP can add, delete, and modify data in your database

PHP can be used to control user-access

PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and even flash
movies. You can also output any text, such as XHTML and XML.

Why PHP?
PHP runs on various platforms (Windows, Linux, UNIX, Mac OS X, etc.)

PHP is compatible with almost all servers used today (Apache, IIS, etc.)

PHP supports a wide range of databases

PHP is free. Download it from the official PHP resource: www.php.net

PHP is easy to learn and runs efficiently on the server side

What's new in PHP 7


PHP 7 is much faster than the previous popular stable release (PHP 5.6)

PHP 7 has improved Error Handling

PHP 7 supports stricter Type Declarations for function arguments

PHP 7 supports new operators (like the spaceship operator: <=>)

BAZIGU ALEX || 0778056780 || 0704923822 3


PHP INSTALLATION
What Do I Need?

To start using PHP, you can:

Find a web host with PHP and MySQL support

Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host with PHP Support

If your server has activated support for PHP you do not need to do anything.

Just create some .php files, place them in your web directory, and the server will automatically parse
them for you.

You do not need to compile anything or install any extra tools.

Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC

However, if your server does not support PHP, you must:

 install a web server


 install PHP
 install a database, such as MySQL
 The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php

PHP SYNTAX
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.

Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

BAZIGU ALEX || 0778056780 || 0704923822 4


The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function
"echo" to output the text "Hello World!" on a web page:

PHP Case Sensitivity

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not
case-sensitive.

In the example below, all three echo statements below are equal and legal:

BAZIGU ALEX || 0778056780 || 0704923822 5


Note: However; all variable names are case-sensitive!

Look at the example below; only the first statement will display the value of the $color variable! This is
because $color, $COLOR, and $coLOR are treated as three different variables:

PHP COMMENTS
Comments in PHP

A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to be
read by someone who is looking at the code.

Comments can be used to:

Let others understand your code

BAZIGU ALEX || 0778056780 || 0704923822 6


Remind yourself of what you did - Most programmers have experienced coming back to their own work a
year or two later and having to re-figure out what they did. Comments can remind you of what you were
thinking when you wrote the code

PHP supports several ways of commenting:

Example: Syntax for single-line comments:

Example: Syntax for multiple-line comments:

Example: Using comments to leave out parts of the code:

BAZIGU ALEX || 0778056780 || 0704923822 7


PHP Variables
Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example.

BAZIGU ALEX || 0778056780 || 0704923822 8


After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5.

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created
the moment you first assign a value to it.

Think of variables as containers for storing data.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)

NOTE: Remember that PHP variable names are case-sensitive!

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

BAZIGU ALEX || 0778056780 || 0704923822 9


The following example will produce the same output as the example above:

The following example will output the sum of two variables:

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

BAZIGU ALEX || 0778056780 || 0704923822 10


PHP automatically associates a data type to the variable, depending on its value. Since the data types
are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the data type expected when
declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type
mismatch.

You will learn more about strict and non-strict requirements, and data type declarations in the PHP
Functions chapter.

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

(i) Local (ii) global (iii) static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:

BAZIGU ALEX || 0778056780 || 0704923822 11


Example: Variable with local scope:

You can have local variables with the same name in different functions, because local variables are
only recognized by the function in which they are declared.

PHP The global Keyword

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name
of the variable. This array is also accessible from within functions and can be used to update global
variables directly.

BAZIGU ALEX || 0778056780 || 0704923822 12


The example above can be rewritten like this:

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes
we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example

Then, each time the function is called, that variable will still have the information it contained from the
last time the function was called.

Note: The variable is still local to the function.

BAZIGU ALEX || 0778056780 || 0704923822 13


PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print.

In this tutorial we use echo or print in almost every example. So, this chapter contains a little more info
about those two output statements.

PHP echo and print Statements

echo and print are more or less the same. They are both used to output data to the screen.

The differences are small: echo has no return value while print has a return value of 1 so it can be used
in expressions. echo can take multiple parameters (although such usage is rare) while print can take one
argument. echo is marginally faster than print.

The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().

Display Text

The following example shows how to output text with the echo command (notice that the text can
contain HTML markup):

Example

Display Variables

The following example shows how to output text and variables with the echo statement:

Example

BAZIGU ALEX || 0778056780 || 0704923822 14


The PHP print Statement

The print statement can be used with or without parentheses: print or print().

Display Text

The following example shows how to output text with the print command (notice that the text can
contain HTML markup):

Example

Display Variables

The following example shows how to output text and variables with the print statement:

BAZIGU ALEX || 0778056780 || 0704923822 15


PHP Data Types
Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

PHP String
A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

BAZIGU ALEX || 0778056780 || 0704923822 16


PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

Rules for integers:

 An integer must have at least one digit


 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary
(base 2) notation

In the following example $x is an integer. The PHP var_dump () function returns the data type and
value:

BAZIGU ALEX || 0778056780 || 0704923822 17


PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The PHP var_dump() function returns the data type and value:

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

Booleans are often used in conditional testing. You will learn more about conditional testing in a later
chapter of this tutorial.

PHP Array
An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type and
value:

Example

BAZIGU ALEX || 0778056780 || 0704923822 18


PHP Object
Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the class, but
each object will have different values for the properties.

Let's assume we have a class named Car. A Car can have properties like model, color, etc. We can
define variables like $model, $color, and so on, to hold the values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the properties.

If you create a __construct() function, PHP will automatically call this function when you create an
object from a class.

BAZIGU ALEX || 0778056780 || 0704923822 19


PHP NULL Value

Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

Example

BAZIGU ALEX || 0778056780 || 0704923822 20


PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.

A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

PHP Strings
A string is a sequence of characters, like "Hello world!".

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

strlen() - Return the Length of a String

The PHP strlen() function returns the length of a string.

Example: Return the length of the string "Hello world!”

BAZIGU ALEX || 0778056780 || 0704923822 21


str_word_count() - Count Words in a String

The PHP str_word_count() function counts the number of words in a string.

strrev() - Reverse a String


The PHP strrev() function reverses a string.

Example: Reverse the string "Hello world!":

BAZIGU ALEX || 0778056780 || 0704923822 22


strpos() - Search For a Text Within a String
The PHP strpos() function searches for a specific text within a string. If a match is found, the function
returns the character position of the first match. If no match is found, it will return FALSE.

Example: Search for the text "world" in the string "Hello world!":

Tip: The first character position in a string is 0 (not 1).

str_replace() - Replace Text within a String


The PHP str_replace() function replaces some characters with some other characters in a string.

Example: Replace the text "world" with "Dolly":

PHP Numbers
In this chapter we will look in depth into Integers, Floats, and Number Strings.

PHP Numbers
One thing to notice about PHP is that it provides automatic data type conversion.

BAZIGU ALEX || 0778056780 || 0704923822 23


So, if you assign an integer value to a variable, the type of that variable will automatically be an integer.
Then, if you assign a string to the same variable, the type will change to a string.

This automatic conversion can sometimes break your code.

PHP Integers

2, 256, -256, 10358, -179567 are all integers.

An integer is a number without any decimal part.

An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems,
and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater
(or lower) than this, will be stored as float, because it exceeds the limit of an integer.

Note: Another important thing to know is that even if 4 * 2.5 is 10, the result is stored as float, because
one of the operands is a float (2.5).

Here are some rules for integers:

 An integer must have at least one digit


 An integer must NOT have a decimal point
 An integer can be either positive or negative

Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with
0x) or octal (8-based - prefixed with 0)

PHP has the following predefined constants for integers:

PHP_INT_MAX - The largest integer supported

PHP_INT_MIN - The smallest integer supported

PHP_INT_SIZE - The size of an integer in bytes

PHP has the following functions to check if the type of a variable is integer:

is_int()

is_integer() - alias of is_int()

BAZIGU ALEX || 0778056780 || 0704923822 24


is_long() - alias of is_int()

Example: Check if the type of a variable is integer:

PHP Floats
A float is a number with a decimal point or a number in exponential form.

2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.

The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent),
and have a maximum precision of 14 digits.

PHP has the following predefined constants for floats (from PHP 7.2):

PHP_FLOAT_MAX - The largest representable floating point number

PHP_FLOAT_MIN - The smallest representable positive floating point number

- PHP_FLOAT_MAX - The smallest representable negative floating point number

PHP_FLOAT_DIG - The number of decimal digits that can be rounded into a float and back without
precision loss

PHP_FLOAT_EPSILON - The smallest representable positive number x, so that x + 1.0 != 1.0

PHP has the following functions to check if the type of a variable is float:

is_float()

BAZIGU ALEX || 0778056780 || 0704923822 25


is_double() - alias of is_float().

Example: Check if the type of a variable is float:

PHP Infinity
A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.

PHP has the following functions to check if a numeric value is finite or infinite:

is_finite()

is_infinite()

However, the PHP var_dump() function returns the data type and value:

Example: Check if a numeric value is finite or infinite:

BAZIGU ALEX || 0778056780 || 0704923822 26


PHP NaN
NaN stands for Not a Number.

NaN is used for impossible mathematical operations.

PHP has the following functions to check if a value is not a number:

is_nan()

However, the PHP var_dump() function returns the data type and value:

Example: Invalid calculation will return a NaN value:

PHP Numerical Strings


The PHP is_numeric() function can be used to find whether a variable is numeric. The function returns
true if the variable is a number or a numeric string, false otherwise.

Example: Check if the variable is numeric:

BAZIGU ALEX || 0778056780 || 0704923822 27


Note: From PHP 7.0: The is_numeric() function will return FALSE for numeric strings in hexadecimal
form (e.g. 0xf4c3b00c), as they are no longer considered as numeric strings.

PHP Casting Strings and Floats to Integers

Sometimes you need to cast a numerical value into another data type.

The (int), (integer), or intval() function are often used to convert a value to an integer.

Example: Cast float and string to integer:

BAZIGU ALEX || 0778056780 || 0704923822 28


PHP Math
PHP has a set of math functions that allows you to perform mathematical tasks on numbers.

PHP pi() Function

The pi() function returns the value of PI:

Example

PHP min() and max() Functions

The min() and max() functions can be used to find the lowest or highest value in a list of arguments:

Example
BAZIGU ALEX || 0778056780 || 0704923822 29
PHP abs() Function

The abs() function returns the absolute (positive) value of a number:

Example

PHP sqrt() Function

The sqrt() function returns the square root of a number:

Example

PHP round() Function

BAZIGU ALEX || 0778056780 || 0704923822 30


The round() function rounds a floating-point number to its nearest integer:

Example

Random Numbers

The rand() function generates a random number:

Example

To get more control over the random number, you can add the optional min and max parameters to
specify the lowest integer and the highest integer to be returned.

For example, if you want a random integer between 10 and 100 (inclusive), use rand(10, 100):

Example

PHP Constants

Constants are like variables except that once they are defined they cannot be changed or undefined.

BAZIGU ALEX || 0778056780 || 0704923822 31


A constant is an identifier (name) for a simple value. The value cannot be changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Note: Unlike variables, constants are automatically global across the entire script.

Create a PHP Constant

To create a constant, use the define() function.

Syntax

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 Case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false

Example: Create a constant with a case-sensitive name:

Example

Create a constant with a case-insensitive name:

BAZIGU ALEX || 0778056780 || 0704923822 32


PHP Constant Arrays

In PHP7, you can create an Array constant using the define() function.

Example: Create an Array constant:

Constants are Global

Constants are automatically global and can be used across the entire script.

Example

BAZIGU ALEX || 0778056780 || 0704923822 33


This example uses a constant inside a function, even if it is defined outside the function:

PHP OPERATORS
Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators


The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.

BAZIGU ALEX || 0778056780 || 0704923822 34


Example of Addition

Addition of Subtraction

Example of Multiplication

BAZIGU ALEX || 0778056780 || 0704923822 35


Example of Division

Example of Modulus

Example of Exponentiation

BAZIGU ALEX || 0778056780 || 0704923822 36


PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.

BAZIGU ALEX || 0778056780 || 0704923822 37


BAZIGU ALEX || 0778056780 || 0704923822 38
PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

BAZIGU ALEX || 0778056780 || 0704923822 39


Example of Increment

Example of Post Increment

Example of pre-decrement

BAZIGU ALEX || 0778056780 || 0704923822 40


Example of post-decrement

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Example for an And.

BAZIGU ALEX || 0778056780 || 0704923822 41


Example for an OR

Example for XOR

Example for &&

BAZIGU ALEX || 0778056780 || 0704923822 42


Example for ||

Example for NOT

PHP String Operators

PHP has two operators that are specially designed for strings.

BAZIGU ALEX || 0778056780 || 0704923822 43


Example of Concatenation

Example of Concatenation Assignment

PHP Array Operators

The PHP array operators are used to compare arrays.

BAZIGU ALEX || 0778056780 || 0704923822 44


Example of Union

Example of Equality

Example of Identity

BAZIGU ALEX || 0778056780 || 0704923822 45


Example of Inequality

Inequality .2

Example of Non-Identity

BAZIGU ALEX || 0778056780 || 0704923822 46


PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Example of Ternary

BAZIGU ALEX || 0778056780 || 0704923822 47


Example of Null Coalescing

BAZIGU ALEX || 0778056780 || 0704923822 48


PHP Conditional Statements
Conditional statements are used to perform different actions based on different conditions.

Very often when you write code, you want to perform different actions for different conditions. You
can use conditional statements in your code to do this.

In PHP, we have the following conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code if that condition is
false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement executes some code if one condition is true.

Syntax

For Example

BAZIGU ALEX || 0778056780 || 0704923822 49


PHP - The if...else Statement

The if...else statement executes some code if a condition is true and another code if that condition is
false.

Syntax

For Example

BAZIGU ALEX || 0778056780 || 0704923822 50


PHP - The if...elseif...else Statement

The if...elseif...else statement executes different codes for more than two conditions.

Syntax

For Example

PHP switch Statement

The switch statement is used to perform different actions based on different conditions.

Use the switch statement to select one of many blocks of code to be executed.

Syntax

BAZIGU ALEX || 0778056780 || 0704923822 51


This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is
a match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically. The default statement is used if no match is found.

For Example

BAZIGU ALEX || 0778056780 || 0704923822 52


BAZIGU ALEX || 0778056780 || 0704923822 53
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The PHP while Loop


The while loop executes a block of code as long as the specified condition is true.

Syntax

Examples

The example below displays the numbers from 1 to 5:

BAZIGU ALEX || 0778056780 || 0704923822 54


Example Explained

 $x = 1; - Initialize the loop counter ($x), and set the start value to 1
 $x <= 5 - Continue the loop as long as $x is less than or equal to 5
 $x++; - Increase the loop counter value by 1 for each iteration

This example counts to 100 by tens:

Example Explained

 $x = 0; - Initialize the loop counter ($x), and set the start value to 0
 $x <= 100 - Continue the loop as long as $x is less than or equal to 100

BAZIGU ALEX || 0778056780 || 0704923822 55


 $x+=10; - Increase the loop counter value by 10 for each iteration

The PHP do...while Loop


The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.

Syntax

Examples

The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to
5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Note: In a do...while loop the condition is tested AFTER executing the statements within the loop.
This means that the do...while loop will execute its statements at least once, even if the condition
is false. See example below.

This example sets the $x variable to 6, then it runs the loop, and then the condition is checked:

BAZIGU ALEX || 0778056780 || 0704923822 56


The PHP for Loop
The for loop is used when you know in advance how many times the script should run.

Syntax

Parameters:

 init counter: Initialize the loop counter value


 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value

Examples

The example below displays the numbers from 0 to 10:

BAZIGU ALEX || 0778056780 || 0704923822 57


Example Explained

 $x = 0; - Initialize the loop counter ($x), and set the start value to 0
 $x <= 10; - Continue the loop as long as $x is less than or equal to 10
 $x++ - Increase the loop counter value by 1 for each iteration

This example counts to 100 by tens:

Example Explained

 $x = 0; - Initialize the loop counter ($x), and set the start value to 0
 $x <= 100; - Continue the loop as long as $x is less than or equal to 100
BAZIGU ALEX || 0778056780 || 0704923822 58
 $x+=10 - Increase the loop counter value by 10 for each iteration.

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.

Examples
The following example will output the values of the given array ($colors):

The following example will output both the keys and the values of the given array ($age):

BAZIGU ALEX || 0778056780 || 0704923822 59


PHP Break and Continue
PHP Break
We have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

PHP Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.

BAZIGU ALEX || 0778056780 || 0704923822 60


This example skips the value of 4:

Break and Continue in While Loop


You can also use break and continue in while loops:

Continue in the While Example

BAZIGU ALEX || 0778056780 || 0704923822 61


BAZIGU ALEX || 0778056780 || 0704923822 62
PHP FUNCTIONS
The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

 A function is a block of statements that can be used repeatedly in a program.


 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function:

Syntax

Note: A function name must start with a letter or an underscore. Function names are NOT case-
sensitive.

Tip: Give the function a name that reflects what the function does!

Consider the example below, we create a function named "writeMsg()". The opening curly brace ( { )
indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the

BAZIGU ALEX || 0778056780 || 0704923822 63


function. The function outputs "Hello world!". To call the function, just write its name followed by
brackets ():

Example

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function
is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs
several different first names, but an equal last name:

BAZIGU ALEX || 0778056780 || 0704923822 64


Example

The following example has a function with two arguments ($fname and $year):

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types
are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when
declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type
mismatches.

BAZIGU ALEX || 0778056780 || 0704923822 65


In the following example we try to send both a number and a string to the function without using strict:

To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the
PHP file.

In the following example we try to send both a number and a string to the function, but here we have
added the strict declaration:

NOTE: The strict declaration forces things to be used in the intended way.

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:

Example

BAZIGU ALEX || 0778056780 || 0704923822 66


PHP Functions - Returning values
To let a function return a value, use the return statement:

PHP Return Type Declarations


PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for
function arguments, by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly (
{ )bracket when declaring the function.

In the following example we specify the return type for the function:

BAZIGU ALEX || 0778056780 || 0704923822 67


You can specify a different return type, than the argument types, but make sure the return is the correct
type:

Passing Arguments by Reference


In PHP, arguments are usually passed by value, which means that a copy of the value is used in the
function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable
that was passed in. To turn a function argument into a reference, the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

BAZIGU ALEX || 0778056780 || 0704923822 68


PHP Arrays
An array stores multiple values in one single variable:

Definition of an Array
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could
look like this:

BAZIGU ALEX || 0778056780 || 0704923822 69


However, what if you want to loop through the cars and find a specific one? And what if you had not
3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values by referring to an
index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

Get The Length of an Array - The count() Function


The count() function is used to return the length (the number of elements) of an array:

Example

PHP Indexed Arrays


There are two ways to create indexed arrays:

BAZIGU ALEX || 0778056780 || 0704923822 70


The index can be assigned automatically (index always starts at 0), like this:

or the index can be assigned manually:

The following example creates an indexed array named $cars, assigns three elements to it, and then
prints a text containing the array values:

Loop through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like this:

BAZIGU ALEX || 0778056780 || 0704923822 71


PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

OR

The named keys can then be used in a script:

Example

Loop through an Associative Array


To loop through and print all the values of an associative array, you could use a foreach loop, like this:

BAZIGU ALEX || 0778056780 || 0704923822 72


PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However,
arrays more than three levels deep are hard to manage for most people.

NOTE: The dimension of an array indicates the number of indices you need to select an element.

 For a two-dimensional array you need two indices to select an element


 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, take a look at the following table:

We can store the data from the table above in a two-dimensional array, like this:

BAZIGU ALEX || 0778056780 || 0704923822 73


Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $cars array we must point to the two indices (row and column):

Example

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have
to point to the two indices):

Example

BAZIGU ALEX || 0778056780 || 0704923822 74


PHP Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:

BAZIGU ALEX || 0778056780 || 0704923822 75


The following example sorts the elements of the $numbers array in ascending numerical order:

Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:

Example

BAZIGU ALEX || 0778056780 || 0704923822 76


The following example sorts the elements of the $numbers array in descending numerical order:

Example

Sort Array (Ascending Order), According to Value - asort()

The following example sorts an associative array in ascending order, according to the value:

Example

BAZIGU ALEX || 0778056780 || 0704923822 77


Sort Array (Ascending Order), According to Key - ksort()

The following example sorts an associative array in ascending order, according to the key:

Example

Sort Array (Descending Order), According to Value - arsort()

The following example sorts an associative array in descending order, according to the value:

Example

BAZIGU ALEX || 0778056780 || 0704923822 78


Sort Array (Descending Order), According to Key - krsort()

The following example sorts an associative array in descending order, according to the key:

Example

PHP Global Variables - Superglobals


Superglobals were introduced in PHP 4.1.0, and are built-in variables that are always available in all
scopes.

Some predefined variables in PHP are "superglobals", which means that they are always accessible,
regardless of scope - and you can access them from any function, class or file without having to do
anything special.

The PHP superglobal variables are:

 $GLOBALS
 $_SERVER

BAZIGU ALEX || 0778056780 || 0704923822 79


 $_REQUEST
 $_POST
 $_GET
 $_FILES
 $_ENV
 $_COOKIE
 $_SESSION

PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in
the PHP script (also from within functions or methods).

PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable.

The example below shows how to use the super global variable $GLOBALS:

Super global variables are built-in variables that are always available in all scopes.

PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script
locations.

The example below shows how to use some of the elements in $_SERVE

BAZIGU ALEX || 0778056780 || 0704923822 80


PHP $_REQUEST

PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an
HTML form.

The example below shows a form with an input field and a submit button. When a user submits the
data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
<form> tag. In this example, we point to this file itself for processing form data. If you wish to use
another PHP file to process form data, replace that with the filename of your choice. Then, we can use
the super global variable $_REQUEST to collect the value of the input field:

BAZIGU ALEX || 0778056780 || 0704923822 81


PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="post". $_POST is also widely used to pass variables.

The example below shows a form with an input field and a submit button. When a user submits the
data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
<form> tag. In this example, we point to the file itself for processing form data. If you wish to use
another PHP file to process form data, replace that with the filename of your choice. Then, we can use
the super global variable $_POST to collect the value of the input field:

BAZIGU ALEX || 0778056780 || 0704923822 82


PHP $_GET
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="get".

$_GET can also collect data sent in the URL.

Assume we have an HTML page that contains a hyperlink with parameters:

When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.

The example below shows the code in "test_get.php":

BAZIGU ALEX || 0778056780 || 0704923822 83


After clicking on the Test $GET, The following will be displayed.

PHP Regular Expressions


What is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern. When you search for data
in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.

BAZIGU ALEX || 0778056780 || 0704923822 84


In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a
modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common
delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to
choose other delimiters such as # or ~.

Regular Expression Functions

PHP provides a variety of functions that allow you to use regular expressions. The preg_match(),
preg_match_all() and preg_replace() functions are some of the most commonly used ones:

Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.

Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

BAZIGU ALEX || 0778056780 || 0704923822 85


Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a string.

Example

Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string:

Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string with another string.

Example

Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:

Regular Expression Modifiers


Modifiers can change how a search is performed.

BAZIGU ALEX || 0778056780 || 0704923822 86


Regular Expression Patterns
Brackets are used to find a range of characters:

Metacharacters
Metacharacters are characters with a special meaning:

Quantifiers

Quantifiers define quantities:

BAZIGU ALEX || 0778056780 || 0704923822 87


Note: If your expression needs to search for one of the special characters you can use a backslash
( \ ) to escape them. For example, to search for one or more question marks you can use the
following expression: $pattern = '/\?+/';

Grouping
You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts
of the pattern to be used as a match.

Example

Use grouping to search for the word "banana" by looking for ba followed by two instances of na:

BAZIGU ALEX || 0778056780 || 0704923822 88


PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a submit button:

When the user fills out the form above and clicks the submit button, the form data is sent for processing
to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php" looks like
this:

The output could be something like this:

The same result could also be achieved using the HTTP GET method:

Example

BAZIGU ALEX || 0778056780 || 0704923822 89


and "welcome_get.php" looks like this:

The code above is quite simple. However, the most important thing is missing. You need to validate
form data to protect your script from malicious code.

NOTE: Think SECURITY when processing PHP forms!. This page does not contain any form
validation, it just shows how you can send and retrieve form data.

However, the next pages will show how to process PHP forms with security in mind! Proper
validation of form data is important to protect your form from hackers and spammers!

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)).
This array holds key/value pairs, where keys are the names of the form controls and values are the input
data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that
they are always accessible, regardless of scope - and you can access them from any function, class or
file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

BAZIGU ALEX || 0778056780 || 0704923822 90


$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all variable names and values
are displayed in the URL). GET also has limits on the amount of information to send. The limitation is
about 2000 characters. However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?


Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information to
send.

Moreover POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

Developers prefer POST for sending form data.

PHP Form Validation


NOTE: Think SECURITY when processing PHP forms!. These pages will show how to process
PHP forms with security in mind. Proper validation of form data is important to protect your
form from hackers and spammers!

The HTML form we will be working at in these chapters, contains various input fields: required and
optional text fields, radio buttons, and a submit button:

BAZIGU ALEX || 0778056780 || 0704923822 91


The validation rules for the form above are as follows:

First we will look at the plain HTML code for the form:

Text Fields
The name, email, and website fields are text input elements, and the comment field is a textarea. The
HTML code looks like this:

BAZIGU ALEX || 0778056780 || 0704923822 92


Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:

The Form Element


The HTML code of the form looks like this:

When the form is submitted, the form data is sent with method="post".

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping
to a different page. This way, the user will get error messages on the same page as the form.

Definition of the htmlspecialchars() function?


The htmlspecialchars() function converts special characters to HTML entities. This means that
it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from
exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

NOTE: PHP Form Security

The $_SERVER["PHP_SELF"] variable can be used by hackers!

BAZIGU ALEX || 0778056780 || 0704923822 93


If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting
(XSS) commands to execute.

NOTE: Cross-site scripting (XSS) is a type of computer security vulnerability typically found in
Web applications. XSS enables attackers to inject client-side script into Web pages viewed by
other users.

Assume we have the following form in a page named "test_form.php":

Now, if a user enters the normal URL in the address bar like "http://www.example.com/test_form.php",
the above code will be translated to:

So far, so good.

However, consider that a user enters the following URL in the address bar:

In this case, the above code will be translated to:

This code adds a script tag and an alert command. And when the page loads, the JavaScript code will
be executed (the user will see an alert box). This is just a simple and harmless example how the
PHP_SELF variable can be exploited.

BAZIGU ALEX || 0778056780 || 0704923822 94


Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the
user to a file on another server, and that file can hold malicious code that can alter the global variables
or submit the form to another address to save the user data, for example.

How To Avoid $_SERVER["PHP_SELF"] Exploits?

$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.

The form code should look like this:

The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to
exploit the PHP_SELF variable, it will result in the following output:

The exploit attempt fails, and no harm is done!

Validate Form Data with PHP


The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.

When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:

<script>location.href('http://www.hacked.com')</script>

- this would not be executed, because it would be saved as HTML escaped code, like this:

&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

 Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP
trim() function)

BAZIGU ALEX || 0778056780 || 0704923822 95


 Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

The next step is to create a function that will do all the checking for us (which is much more convenient
than writing the same code over and over again).

We will name the function test_input().

Now, we can check each $_POST variable

with the test_input() function, and the script looks like this:

Example

<!DOCTYPE HTML>
<html> <head> </head> <body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender: BAZIGU ALEX || 0778056780 || 0704923822 96
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been
submitted - and it should be validated. If it has not been submitted, skip the validation and display a
blank form.

However, in the example above, all input fields are optional. The script works fine even if the user does
not enter any data.

PHP - Required Fields


From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender"
fields are required. These fields cannot be empty and must be filled out in the HTML form.

BAZIGU ALEX || 0778056780 || 0704923822 97


In the previous example, all input fields were optional.

In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and
$websiteErr. These error variables will hold error messages for the required fields. We have also added
an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the
PHP empty() function). If it is empty, an error message is stored in the different error variables, and if
it is not empty, it sends the user input data through the test_input() function:

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]); BAZIGU ALEX || 0778056780 || 0704923822 98
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which generates the correct
error message if needed (that is if the user tries to submit the form without filling out the required
fields):

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]); BAZIGU ALEX || 0778056780 || 0704923822 99
}

if (empty($_POST["comment"])) {
$comment = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br> 10
BAZIGU ALEX || 0778056780 || 0704923822
<input type="submit" name="submit" value="Submit"> 0
</form>

<?php
echo "<h2>Your Input:</h2>";
Code Output

10
BAZIGU ALEX || 0778056780 || 0704923822
1
The next step is to validate the input data, that is "Does the Name field contain only letters and
whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out,
"Does the Website field contain a valid URL?”

PHP Forms - Validate E-mail and URL


This section demonstrates how to validate names, e-mails, and URLs.

PHP - Validate Name


The code below shows a simple way to check if the name field only contains letters, dashes, apostrophes
and whitespaces. If the value of the name field is not valid, then store an error message:

10
BAZIGU ALEX || 0778056780 || 0704923822
2
NOTE: The preg_match() function searches a string for pattern, returning true if the pattern exists, and
false otherwise.

PHP - Validate E-mail


The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var()
function.

In the code below, if the e-mail address is not well-formed, then store an error message:

PHP - Validate URL


The code below shows a way to check if a URL address syntax is valid (this regular expression also
allows dashes in the URL). If the URL address syntax is not valid, then store an error message:

PHP - Validate Name, E-mail, and URL

Now, the script looks like this:

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required"; 10
} BAZIGU ALEX || 0778056780 || 0704923822
3
else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
10
BAZIGU ALEX || 0778056780 || 0704923822
function test_input($data) { 4
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
10
BAZIGU ALEX || 0778056780 || 0704923822
</body> 5
</html>
10
BAZIGU ALEX || 0778056780 || 0704923822
6
PHP - AJAX Introduction
AJAX is about updating parts of a web page, without reloading the whole page.

What is AJAX?
AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the
server behind the scenes. This means that it is possible to update parts of a web page, without reloading
the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works

AJAX is Based on Internet Standards


AJAX is based on internet standards, and uses a combination of:

 XMLHttpRequest object (to exchange data asynchronously with a server)

10
BAZIGU ALEX || 0778056780 || 0704923822
7
 JavaScript/DOM (to display/interact with the information)
 CSS (to style the data)
 XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!

Google Suggest. AJAX was made popular in 2005 by Google, with Google Suggest.

Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in
Google's search box, a JavaScript sends the letters off to a server and the server returns a list of
suggestions.

FUNCTIONS OF AJAX IN PHP


1) AJAX is used to create more interactive applications

AJAX PHP Example


The following example will demonstrate how a web page can communicate with a web server while a
user type characters in an input field:

Example Explained
In the example above, when a user types a character in the input field, a function called "showHint()"
is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

10
BAZIGU ALEX || 0778056780 || 0704923822
8
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint
placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
 Notice that q parameter is added to the url (gethint.php?q="+str)
 And the str variable holds the content of the input field

The PHP File - "gethint.php"

10
BAZIGU ALEX || 0778056780 || 0704923822
9
The PHP file checks an array of names, and returns the corresponding name(s) to the browser:

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct values


echo $hint === "" ? "no suggestion" : $hint;
?>

2) AJAX can be used for interactive communication with a database.

AJAX Database Example

11
BAZIGU ALEX || 0778056780 || 0704923822
0
The following example will demonstrate how a web page can fetch information from a database with
AJAX:

Example Explained - The MySQL Database


The database table we use in the example above looks like this:

In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed.

The function is triggered by the onchange event.

Here is the HTML code:

11
BAZIGU ALEX || 0778056780 || 0704923822
1
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and
exit the function. If a person is selected, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getuser.php".

The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an
HTML table:

<!DOCTYPE html>
<html> <head>
<style>
table { 11
BAZIGU ALEX || 0778056780 || 0704923822
width: 100%; 2
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>"; 11
echo "<td>" . $row['Hometown'] . "</td>"; BAZIGU ALEX || 0778056780 || 0704923822 3
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

PHP opens a connection to a MySQL server. The correct person is found and an HTML table is
created, filled with data, and sent back to the "txtHint" placeholder.

3) AJAX can be used for interactive communication with an XML file.

AJAX XML Example

The following example will demonstrate how a web page can fetch information from an XML file
with AJAX:

Example Explained - The HTML Page


When a user selects a CD in the dropdown list above, a function called "showCD()" is executed. The
function is triggered by the "onchange" event:

<html>
<head>
<script>
function showCD(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return; 11
BAZIGU ALEX || 0778056780 || 0704923822
} 4
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
The showCD() function does the following:

 Check if a CD is selected
 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "getcd.php".

The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and
returns the result as HTML:

11
BAZIGU ALEX || 0778056780 || 0704923822
5
<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();


$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++) {


//Process only element nodes
if ($x->item($i)->nodeType==1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y=($x->item($i)->parentNode);
}
}
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++) {
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>

When the CD query is sent from the JavaScript to the PHP page, the following happens:

 PHP creates an XML DOM object


 Find all <artist> elements that matches the name sent from the JavaScript
 Output the album information (send to the "txtHint" placeholder).

4) AJAX can be used to create more user-friendly and interactive searches.

AJAX Live Search

The following example will demonstrate a live search, where you get search results while you type.

Live search has many benefits compared to traditional searching:

 Results are shown as you type


11
BAZIGU ALEX || 0778056780 || 0704923822
6
 Results narrow as you continue typing
 If results become too narrow, remove characters to see a broader result

Search for a balexinfotech.com page in the input field below:

The results in the example above are found in an XML file (links.xml). To make this example small
and simple, only six results are available.

Example Explained - The HTML Page


When a user types a character in the input field above, the function "showResult()" is executed. The
function is triggered by the "onkeyup" event:

<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>

11
BAZIGU ALEX || 0778056780 || 0704923822
7
Source code explanation:
If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder
and exits the function.

If the input field is not empty, the showResult() function executes the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the input field)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "livesearch.php".

The source code in "livesearch.php" searches an XML file for titles matching the search string and
returns the result:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL


$q=$_GET["q"];

//lookup all links from the xml file if length of q>0


if (strlen($q)>0) {
$hint="";
for($i=0; $i<($x->length); $i++) {
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1) {
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
if ($hint=="") {
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}

11
BAZIGU ALEX || 0778056780 || 0704923822
8
else {
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}

// Set output to "no suggestion" if no hint was found


// or to the correct values
if ($hint=="") {
$response="no suggestion";
} else {
$response=$hint;
}

//output the response


echo $response;
?>
If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

 Load an XML file into a new XML DOM object


 Loop through all <title> elements to find matches from the text sent from the JavaScript
 Sets the correct url and title in the "$response" variable. If more than one match is found, all
matches are added to the variable
 If no matches are found, the $response variable is set to "no suggestion"

11
BAZIGU ALEX || 0778056780 || 0704923822
9
12
BAZIGU ALEX || 0778056780 || 0704923822
0

You might also like