PHP and MySQL Handbook
PHP and MySQL Handbook
DEPARTMENT OF INFORMATION
TECHNOLOGY
STUDENT’S COPY
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.
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"
It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!
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"
PHP can create, open, read, write, delete, and close files on the server
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.)
Install a web server on your own PC, and then install PHP and MySQL
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.
PHP SYNTAX
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
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:
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:
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.
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example.
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.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
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)
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:
In the example above, notice that we did not have to tell PHP which data type the variable is.
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.
The scope of a variable is the part of the script where the variable can be referenced/used.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
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.
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.
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.
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.
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 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
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:
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:
In the following example $x is an integer. The PHP var_dump () function returns the data type and
value:
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
PHP Boolean
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
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.
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.
Example
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!".
In this chapter we will look at some commonly used functions to manipulate strings.
Example: Search for the text "world" in the string "Hello world!":
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.
PHP Integers
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).
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 functions to check if the type of a variable is integer:
is_int()
PHP Floats
A float is a number with a decimal point or a number in exponential form.
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_DIG - The number of decimal digits that can be rounded into a float and back without
precision loss
PHP has the following functions to check if the type of a variable is float:
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:
is_nan()
However, the PHP var_dump() function returns the data type and value:
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
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
Example
Example
Example
Random Numbers
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.
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.
Syntax
Parameters:
Example
In PHP7, you can create an Array constant using the define() function.
Constants are automatically global and can be used across the entire script.
Example
PHP OPERATORS
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
Addition of Subtraction
Example of Multiplication
Example of Modulus
Example of Exponentiation
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.
The PHP comparison operators are used to compare two values (number or string):
Example of pre-decrement
PHP has two operators that are specially designed for strings.
Example of Equality
Example of Identity
Inequality .2
Example of Non-Identity
The PHP conditional assignment operators are used to set a value depending on conditions:
Example of Ternary
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.
Syntax
For Example
The if...else statement executes some code if a condition is true and another code if that condition is
false.
Syntax
For Example
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
For Example
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
For Example
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
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
Syntax
Examples
$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
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
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:
Syntax
Parameters:
Examples
$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
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.
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):
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.
PHP has more than 1000 built-in functions, and in addition you can create your own custom 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.
Besides the built-in PHP functions, it is possible to create your own functions.
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
Example
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:
The following example has a function with two arguments ($fname and $year):
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.
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.
Example
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:
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
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:
An array can hold many values under a single name, and you can access the values by referring to an
index number.
Example
The following example creates an indexed array named $cars, assigns three elements to it, and then
prints a text containing the array values:
OR
Example
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.
We can store the data from the table above in a two-dimensional array, like this:
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
The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
In this chapter, we will go through the following PHP array sort functions:
The following example sorts the elements of the $cars array in ascending alphabetical order:
The following example sorts the elements of the $cars array in descending alphabetical order:
Example
Example
The following example sorts an associative array in ascending order, according to the value:
Example
The following example sorts an associative array in ascending order, according to the key:
Example
The following example sorts an associative array in descending order, according to the value:
Example
The following example sorts an associative array in descending order, according to the key:
Example
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.
$GLOBALS
$_SERVER
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
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:
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:
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.
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.
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.
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 ~.
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
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
Metacharacters
Metacharacters are characters with a special meaning:
Quantifiers
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:
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 same result could also be achieved using the HTTP GET method:
Example
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!
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.
Note: GET should NEVER be used for sending passwords or other sensitive information!
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.
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:
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:
When the form is submitted, the form data is sent with method="post".
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.
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.
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:
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.
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:
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:
<script>location.href('http://www.hacked.com')</script>
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)
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).
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.
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;
}
?>
<?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?”
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.
In the code below, if the e-mail address is not well-formed, then store an error message:
<!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 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.
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)
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.
Example Explained
In the example above, when a user types a character in the input field, a function called "showHint()"
is executed.
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.
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";
}
}
}
}
11
BAZIGU ALEX || 0778056780 || 0704923822
0
The following example will demonstrate how a web page can fetch information from a database with
AJAX:
In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed.
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:
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.
The following example will demonstrate how a web page can fetch information from an XML file
with AJAX:
<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 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"];
$x=$xmlDoc->getElementsByTagName('ARTIST');
$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:
The following example will demonstrate a live search, where you get search results while you type.
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.
<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:
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');
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>";
}
}
}
}
}
11
BAZIGU ALEX || 0778056780 || 0704923822
9
12
BAZIGU ALEX || 0778056780 || 0704923822
0