Advanced PHP Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 246

Chapter 18

PHP Date and Time
In this tutorial you will learn how to extract or format the date and time in PHP.

The PHP Date() Function
The PHP date() function convert a timestamp to a more readable date and time.

The computer stores dates and times in a format called UNIX Timestamp, which
measures time as a number of seconds since the beginning of the Unix epoch
(midnight Greenwich Mean Time on January 1, 1970 i.e. January 1, 1970 00:00:00
GMT ).

Since this is an impractical format for humans to read, PHP converts a timestamp
to a format that is readable to humans and dates from your notation into a
timestamp the computer understands. The syntax of the PHP date() function can
be given with.

date(format, timestamp)

The format parameter in the date() function is required which specifies the format


of returned date and time. However the timestamp is an optional parameter, if
not included then current date and time will be used. The following statement
displays today's date:

Example
Run this code »
<?php
$today=date("d/m/Y");
echo$today;
?>

Note: The PHP date() function return the current date and time according to the
built-in clock of the web server on which the script has been executed.
Formatting the Dates and Times with PHP
The format parameter of the date() function is in fact a string that can contain
multiple characters allowing you to generate a date string containing various
components of the date and time, like day of the week, AM or PM, etc. Here are
some the date-related formatting characters that are commonly used in format
string:

 d - Represent day of the month; two digits with leading zeros (01 or 31)
 D - Represent day of the week in text as an abbreviation (Mon to Sun)
 m - Represent month in numbers with leading zeros (01 or 12)
 M - Represent month in text, abbreviated (Jan to Dec)
 L- represent the day of the week in full (Monday to Sunday)
 F- represent month in text(January to December)
 y - Represent year in two digits (08 or 14)
 Y - Represent year in four digits (2008 or 2014)

The parts of the date can be separated by inserting other characters, like hyphens
(-), dots (.), slashes (/), or spaces to add additional visual formatting.

Example
Run this code »
<?php
echodate("d/m/Y")."<br>";
echodate("d-m-Y")."<br>";
echodate("d.m.Y");
?>

Tip: You can use the PHP date() function to automatically update the copyright


duration on your website, like: Copyright &copy; 2010-<?php echo date("Y")?>.

Similarly you can use the following characters to format the time string:

 h - Represent hour in 12-hour format with leading zeros (01 to 12)


 H - Represent hour in in 24-hour format with leading zeros (00 to 23)
 i - Represent minutes with leading zeros (00 to 59)
 s - Represent seconds with leading zeros (00 to 59)
 a - Represent lowercase ante meridiem and post meridiem (am or pm)
 A - Represent uppercase Ante meridiem and Post meridiem (AM or PM)

The PHP code in the following example displays the date in different formats:

Example
Run this code »
<?php
echodate("h:i:s")."<br>";
echodate("F d, Y h:i:s A")."<br>";
echodate("h:i a");
?>

The PHP time() Function
The time() function is used to get the current time as a Unix timestamp (the
number of seconds since the beginning of the Unix epoch: January 1 1970
00:00:00 GMT).

Example
Run this code »
<?php
// Executed at March 05, 2014 07:19:18
$timestamp=time();
echo($timestamp);
?>

The above example produce the following output.

1394003958
We can convert this timestamp to a human readable date through passing it to
the previously introduce date() function.

Example
Run this code »
<?php
$timestamp=1394003958;
echo(date("F d, Y h:i:s",$timestamp));
?>

The above example produce the following output.


March 05, 2014 07:19:18

The PHP mktime() Function
The mktime() function is used to create the timestamp based on a specific date
and time. If no date and time is provided, the timestamp for the current date and
time is returned.

The syntax of the mktime() function can be given with:


mktime(hour, minute, second, month, day, year)

The following example displays the timestamp corresponding to 3:20:12 pm on


May 10, 2014:

Example
Run this code »
<?php
// Create the timestamp for a particular date
echo mktime(15,20,12,5,10,2014);
?>

The above example produces the following output.

1399735212
Note: You can leave out as many arguments as you like, and the value
corresponding to the current time will be used instead. If you omit all the
arguments, the mktime() function will return the UNIX timestamp corresponding
to the current date and time, just like time().

The mktime() function can be used to find the weekday name corresponding to a


particular date. To do this, simply use the 'l' (lowercase 'L') character with your
timestamp, as in the following example, which displays the day that falls on April
1, 2014:

Example
Run this code »
<?php
// Get the weekday name of a particular date
echo date('l',mktime(0,0,0,4,1,2014));
?>

The above example produce the following output.

Tuesday
The mktime() function can also be used to find a particular date in future after a
specific time period. As in the following example, which displays the date which
falls on after 30 month from the current date?

Example
Run this code »
<?php
// Executed at March 05, 2014
$futureDate=mktime(0,0,0,date("m")+30,date("d"),date("Y"));
echodate("d/m/Y",$futureDate);
?>

The above example produce the following output.

05/09/2016

Complete PHP Date Reference


Please check out the PHP Date/Time Functions reference section for a complete
list of all the useful date and time functions available in PHP.
Chapter 19

PHP Include and Require Files
In this tutorial you will learn how to include and evaluate the files in PHP.

Including a PHP File into Another PHP File


The include() and require() statement allow you to include the code contained
in a PHP file within another PHP file. Including a file produces the same result as
copying the script from the file specified and pasted into the location where it is
called.

You can save a lot of time and work through including files — Just store a block
of code in a separate file and include it wherever you want using
the include() and require() statements instead of typing the entire block of
code multiple times. A typical example is including the header, footer and menu
file within all the pages of a website.

The basic syntax of the include() and require() statement can be given with:


include("path/to/filename"); -Or- include "path/to/filename";
require("path/to/filename"); -Or- require "path/to/filename";

Tip: Like the print and echo statements, you can omit the parentheses while


using the include and require statements as demonstrated above.

The following example will show you how to include the common header, footer
and menu codes which are stored in separate 'header.php', 'footer.php' and
'menu.php' files respectively, within all the pages of your website. Using this
technique you can update all pages of the website at once by making the
changes to just one file, this saves a lot of repetitive work.
Example
Run this code »

<!DOCTYPE html>
<html lang="en">
<head>
<title>Tutorial Republic</title>
</head>
<body>
<?phpinclude"header.php";?>
<?phpinclude"menu.php";?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?phpinclude"footer.php";?>
</body>
</html>

Difference Between include and require Statements


You might be thinking if we can include files using the include() statement then
why we need require(). Typically the require() statement operates
like include().

The only difference is — the include() statement will only generate a PHP


warning but allow script execution to continue if the file to be included can't be
found, whereas the require() statement will generate a fatal error and stops the
script execution.

Example
Run this code »

<?phprequire"my_variables.php";?>
<?phprequire"my_functions.php";?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?phpdisplayTitle($home_page);?></title>
</head>
<body>
<?phpinclude"header.php";?>
<?phpinclude"menu.php";?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?phpinclude"footer.php";?>
</body>
</html>
Tip: It is recommended to use the require() statement if you're including the
library files or files containing the functions and configuration variables that are
essential for running your application, such as database configuration file.

The include_once and require_once Statements


If you accidentally include the same file (typically functions or classes files) more
than one time within your code using the include or require statements, it may
cause conflicts. To prevent this situation, PHP
provides include_once and require_once statements. These statements behave
in the same way as include and require statements with one exception.

The include_once and require_once statements will only include the file once


even if asked to include it a second time i.e. if the specified file has already been
included in a previous statement, the file is not included again. To better
understand how it works, let's check out an example. Suppose we've a
'my_functions.php' file with the following code:

Example
Run this code »

<?php
functionmultiplySelf($var){
$var*=$var;// multiply variable by itself
echo$var;
}
?>
Here's is the PHP script within which we've included the 'my_functions.php' file.

Example
Run this code »

<?php
// Including file
require"my_functions.php";
// Calling the function
multiplySelf(2);// Output: 4
echo"<br>";

// Including file once again


require"my_functions.php";
// Calling the function
multiplySelf(5);// Doesn't execute
?>
When you run the above script, you will see the error message something like
this: "Fatal error: Cannot redeclare multiplySelf()". This occurs because the
'my_functions.php' included twice, this means the function multiplySelf() is
defined twice, which caused PHP to stop script execution and generate fatal error.
Now rewrite the above example with require_once.

Example
Run this code »

<?php
// Including file
require_once"my_functions.php";
// Calling the function
multiplySelf(2);// Output: 4
echo"<br>";

// Including file once again


require_once"my_functions.php";
// Calling the function
multiplySelf(5);// Output: 25
?>
As you can see, by using require_once instead of require, the script works as we
expected.
Chapter 20

PHP File System
In this tutorial you will learn how to create, access (or read) and manipulate files
dynamically using the PHP's file system functions.

Working with Files in PHP


Since PHP is a server side programming language, it allows you to work with files
and directories stored on the web server. In this tutorial you will learn how to
create, access, and manipulate files on your web server using the PHP file system
functions.

Opening a File with PHP fopen() Function


To work with a file you first need to open the file. The PHP fopen() function is
used to open a file. The basic syntax of this function can be given with:
fopen(filename, mode)

The first parameter passed to fopen() specifies the name of the file you want to
open, and the second parameter specifies in which mode the file should be
opened. For example:

Example
Run this code »

<?php
$handle=fopen("data.txt","r");
?>
The file may be opened in one of the following modes:

Modes What it does

r Open the file for reading only.

r+ Open the file for reading and writing.

w Open the file for writing only and clears the contents of file. If the
file does not exist, PHP will attempt to create it.

w+ Open the file for reading and writing and clears the contents of
file. If the file does not exist, PHP will attempt to create it.

a Append. Opens the file for writing only. Preserves file content by
writing to the end of the file. If the file does not exist, PHP will
attempt to create it.

a+ Read/Append. Opens the file for reading and writing. Preserves


file content by writing to the end of the file. If the file does not
exist, PHP will attempt to create it.

x Open the file for writing only. Return FALSE and generates an


error if the file already exists. If the file does not exist, PHP will
attempt to create it.

x+ Open the file for reading and writing; otherwise it has the same
behavior as 'x'.

If you try to open a file that doesn't exist, PHP will generate a warning message.
So, to avoid these error messages you should always implement a simple check
whether a file or directory exists or not before trying to access it, with the
PHP file_exists() function.
Example
Run this code »

<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Attempt to open the file
$handle=fopen($file,"r");
}else{
echo"ERROR: File does not exist.";
}
?>
Tip: Operations on files and directories are prone to errors. So it's a good
practice to implement some form of error checking so that if an error occurs your
script will handle the error gracefully. See the tutorial on PHP error handling.

Closing a File with PHP fclose() Function


Once you've finished working with a file, it needs to be closed.
The fclose() function is used to close the file, as shown in the following
example:

Example
Run this code »

<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Open the file for reading
$handle=fopen($file,"r")ordie("ERROR: Cannot open the file.");

/* Some code to be executed */


// Closing the file handle
fclose($handle);
}else{
echo"ERROR: File does not exist.";
}
?>
Note: Although PHP automatically closes all open files when script terminates,
but it's a good practice to close a file after performing all the operations.

Reading from Files with PHP fread() Function


Now that you have understood how to open and close files. In the following
section you will learn how to read data from a file. PHP has several functions for
reading data from a file. You can read from just one character to the entire file
with a single operation.

Reading Fixed Number of Characters


The fread() function can be used to read a specified number of characters from
a file. The basic syntax of this function can be given with.
fread(file handle, length in bytes)

This function takes two parameter — A file handle and the number of bytes to
read. The following example reads 20 bytes from the "data.txt" file including
spaces. Let's suppose the file "data.txt" contains a paragraph of text "The quick
brown fox jumps over the lazy dog."

Example
Run this code »

<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Open the file for reading
$handle=fopen($file,"r")ordie("ERROR: Cannot open the file.");
// Read fixed number of bytes from the file
$content=fread($handle,"20");

// Closing the file handle


fclose($handle);

// Display the file content


echo$content;
}else{
echo"ERROR: File does not exist.";
}
?>

The above example will produce the following output:

The quick brown fox

Reading the Entire Contents of a File


The fread() function can be used in conjugation with the filesize() function to
read the entire file at once. The filesize() function returns the size of the file in
bytes.

Example
Run this code »

<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Open the file for reading
$handle=fopen($file,"r")or die("ERROR: Cannot open the file.");

// Reading the entire file


$content=fread($handle,filesize($file));

// Closing the file handle


fclose($handle);

// Display the file content


echo$content;
}else{
echo"ERROR: File does not exist.";
}
?>
The above example will produce the following output:

The quick brown fox jumps over the lazy dog.

The easiest way to read the entire contents of a file in PHP is with
the readfile() function. This function allows you to read the contents of a file
without needing to open it. The following example will generate the same output
as above example:

Example
Run this code »

<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Reads and outputs the entire file
readfile($file)ordie("ERROR: Cannot open the file.");
}else{
echo"ERROR: File does not exist.";
}
?>
The above example will produce the following output:

The quick brown fox jumps over the lazy dog.

Another way to read the whole contents of a file without needing to open it is
with the file_get_contents() function. This function accepts the name and path
to a file, and reads the entire file into a string variable. Here's an example:

Example
<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Reading the entire file into a string
$content=file_get_contents($file)ordie("ERROR: Cannot open the
file.");

// Display the file content


echo $content;
}else{
echo"ERROR: File does not exist.";
}
?>
One more method of reading the whole data from a file is the
PHP's file() function. It does a similar job to file_get_contents() function, but
it returns the file contents as an array of lines, rather than a single string. Each
element of the returned array corresponds to a line in the file.

To process the file data, you need to iterate over the array using a foreach loop.
Here's an example, which reads a file into an array and then displays it using the
loop:

Example
Run this code »

<?php
$file="data.txt";

// Check the existence of file


if(file_exists($file)){
// Reading the entire file into an array
$arr=file($file)ordie("ERROR: Cannot open the file.");
foreach($arras$line){
echo$line;
}
}else{
echo"ERROR: File does not exist.";
}
?>

Writing the Files Using PHP fwrite() Function


Similarly, you can write data to a file or append to an existing file using the
PHP fwrite() function. The basic syntax of this function can be given with:
fwrite(file handle, string)

The fwrite() function takes two parameter — A file handle and the string of


data that is to be written, as demonstrated in the following example:

Example
Run this code »

<?php
$file="note.txt";

// String of data to be written


$data="The quick brown fox jumps over the lazy dog.";

// Open the file for writing


$handle=fopen($file,"w")ordie("ERROR: Cannot open the file.");

// Write data to the file


fwrite($handle,$data)ordie("ERROR: Cannot write the file.");

// Closing the file handle


fclose($handle);

echo"Data written to the file successfully.";


?>
In the above example, if the "note.txt" file doesn't exist PHP will automatically
create it and write the data. But, if the "note.txt" file already exist, PHP will erase
the contents of this file, if it has any, before writing the new data, however if you
just want to append the file and preserve existing contents just use
the mode a instead of w in the above example.

An alternative way is using the file_put_contents() function. It is counterpart


of file_get_contents() function and provides an easy method of writing the
data to a file without needing to open it. This function accepts the name and
path to a file together with the data to be written to the file. Here's an example:

Example
Run this code »

<?php
$file="note.txt";

// String of data to be written


$data="The quick brown fox jumps over the lazy dog.";

// Write data to the file


file_put_contents($file,$data)ordie("ERROR: Cannot write the
file.");

echo"Data written to the file successfully.";


?>
If the file specified in the file_put_contents() function already exists, PHP will
overwrite it by default. If you would like to preserve the file's contents you can
pass the special FILE_APPEND flag as a third parameter to
the file_put_contents() function. It will simply append the new data to the file
instead of overwitting it. Here's an example:

Example
Run this code »

<?php
$file="note.txt";

// String of data to be written


$data="The quick brown fox jumps over the lazy dog.";

// Write data to the file


file_put_contents($file,$data,FILE_APPEND)ordie("ERROR: Cannot
write the file.");

echo"Data written to the file successfully.";


?>

Renaming Files with PHP rename() Function


You can rename a file or directory using the PHP's rename() function, like this:
Example
Run this code »

<?php
$file="file.txt";

// Check the existence of file


if(file_exists($file)){
// Attempt to rename the file
if(rename($file,"newfile.txt")){
echo"File renamed successfully.";
}else{
echo"ERROR: File cannot be renamed.";
}
}else{
echo"ERROR: File does not exist.";
}
?>

Removing Files with PHP unlink() Function


You can delete files or directories using the PHP's unlink() function, like this:

Example
Run this code »

<?php
$file="note.txt";

// Check the existence of file


if(file_exists($file)){
// Attempt to delete the file
if(unlink($file)){
echo"File removed successfully.";
}else{
echo"ERROR: File cannot be removed.";
}
}else{
echo"ERROR: File does not exist.";
}
?>
In the next chapter we will learn more about parsing directories or folders in PHP.

PHP Filesystem Functions


The following table provides the overview of some other useful PHP filesystem
functions that can be used for reading and writing the files dynamically.

Function Description

fgetc() Reads a single character at a time.

fgets() Reads a single line at a time.

fgetcsv() Reads a line of comma-separated values.

filetype() Returns the type of the file.

feof() Checks whether the end of the file has been


reached.

is_file() Checks whether the file is a regular file.

is_dir() Checks whether the file is a directory.

is_executable() Checks whether the file is executable.

realpath() Returns canonicalized absolute pathname.

rmdir() Removes an empty directory.

Please check out the PHP filesystem reference for other useful PHP filesystem
functions.
Chapter 21

PHP Parsing Directories
In this tutorial you will learn how to process directories or folders using PHP.

Working with Directories in PHP


In the previous chapter you've learned how to work with files in PHP. Similarly,
PHP also allows you to work with directories on the file system, for example, you
can open a directory and read its contents, create or delete a directory, list all
files in the directory, and so on.

Creating a New Directory


You can create a new and empty directory by calling the PHP mkdir() function
with the path and name of the directory to be created, as shown in the example
below:

Example
Run this code »

<?php
// The directory path
$dir="testdir";

// Check the existence of directory


if(!file_exists($dir)){
// Attempt to create directory
if(mkdir($dir)){
echo"Directory created successfully.";
}else{
echo"ERROR: Directory could not be created.";
}
}else{
echo"ERROR: Directory already exists.";
}
?>
To make the mkdir() function work, the parent directories in the directory path
parameter has to exist already, for example, if you specify the directory path
as testdir/subdir than the testdir has to exist otherwise PHP will generate an
error.

Copying Files from One Location to Another


You can copy a file from one location to another by calling PHP copy() function
with the file's source and destination paths as arguments. If the destination file
already exists it'll be overwritten. Here's an example which creates a copy of
"example.txt" file inside backup folder.

Example
Run this code »

<?php
// Source file path
$file="example.txt";

// Destination file path


$newfile="backup/example.txt";

// Check the existence of file


if(file_exists($file)){
// Attempt to copy file
if(copy($file,$newfile)){
echo"File copied successfully.";
}else{
echo"ERROR: File could not be copied.";
}
}else{
echo"ERROR: File does not exist.";
}
?>
To make this example work, the target directory which is backup and the source
file i.e. "example.txt" has to exist already; otherwise PHP will generate an error.
Listing All Files in a Directory
You can use the PHP scandir() function to list files and directories inside the
specified path.

Now we're going to create a custom function that will recursively list all files in a
directory using PHP. This script will be helpful if you're working with deeply
nested directory structure.

Example
Run this code »

<?php
// Define a function to output files in a directory
functionoutputFiles($path){
// Check directory exists or not
if(file_exists($path)&& is_dir($path)){
// Scan the files in this directory
$result=scandir($path);

// Filter out the current (.) and parent (..) directories


$files=array_diff($result,array('.','..'));

if(count($files)>0){
// Loop through retuned array
foreach($filesas$file){
if(is_file("$path/$file")){
// Display filename
echo$file."<br>";
}elseif(is_dir("$path/$file")){
// Recursively call the function if directories found
outputFiles("$path/$file");
}
}
}else{
echo"ERROR: No files found in the directory.";
}
}else{
echo"ERROR: The directory does not exist.";
}
}
// Call the function
outputFiles("mydir");
?>

Listing All Files of a Certain Type


While working on directory and file structure, sometimes you might need to find
out certain types of files within the directory, for example, listing
only .text or .png files, etc. You can do this easily with the PHP glob() function,
which matches files based on the pattern.

The PHP code in the following example will search the documents directory and
list all the files with .text extension. It will not search the subdirectories.

Example
Run this code »

<?php
/* Search the directory and loop through
returned array containing the matched files */
foreach(glob("documents/*.txt")as$file){
echobasename($file)." (size: ".filesize($file)." bytes)"."<br>";
}
?>
The glob() function can also be used to find all the files within a directory or its
subdirectories. The function defined in the following example will recursively list
all files within a directory, just like we've done in previous example with
the scandir() function.

Example
Run this code »

<?php
// Define a function to output files in a directory
functionoutputFiles($path){
// Check directory exists or not
if(file_exists($path)&&is_dir($path)){
// Search the files in this directory
$files=glob($path."/*");
if(count($files)>0){
// Loop through retuned array
foreach($filesas$file){
if(is_file("$file")){
// Display only filename
echobasename($file)."<br>";
}elseif(is_dir("$file")){
// Recursively call the function if directories found
outputFiles("$file");
}
}
}else{
echo"ERROR: No such file found in the directory.";
}
}else{
echo"ERROR: The directory does not exist.";
}
}

// Call the function


outputFiles("mydir");
?>
Chapter 22

PHP File Upload
In this tutorial you'll learn how to upload a file to the remote web server with
PHP.

Uploading Files with PHP


In this tutorial we will learn how to upload files on remote server using a Simple
HTML form and PHP. You can upload any kind of file like images, videos, ZIP files,
Microsoft Office documents, PDFs, as well as executables files and a wide range
of other file types.

Step 1: Creating an HTML form to upload the file


The following example will create a simple HTML form that can be used to
upload files.

Example
Download

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="upload-
manager.php"method="post"enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file"name="photo"id="fileSelect">
<input type="submit"name="submit"value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats
allowed to a max size of 5 MB.</p>
</form>
</body>
</html>

Note: In addition to a file-select field the upload form must use the HTTP


post method and must contain an enctype="multipart/form-data" attribute. This
attribute ensures that the form data is encoded as mulitpart MIME data — which
is required for uploading the large quantities of binary data such as image, audio,
video, etc.

Step 2: Processing the uploaded file


Here's the complete code of our "upload-manager.php" file. It will store the
uploaded file in a "upload" folder on permanent basis as well as implement some
basic security check like file type and file size to ensure that users upload the
correct file type and within the allowed limit.

Example
Download

<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"]=="POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"])&&$_FILES["photo"]["error"]==0){
$allowed=array("jpg"=>"image/jpg","jpeg"=>"image/jpeg","gif"=>"im
age/gif","png"=>"image/png");
$filename=$_FILES["photo"]["name"];
$filetype=$_FILES["photo"]["type"];
$filesize=$_FILES["photo"]["size"];

// Verify file extension


$ext=pathinfo($filename,PATHINFO_EXTENSION);
if(!array_key_exists($ext,$allowed))die("Error: Please select a
valid file format.");

// Verify file size - 5MB maximum


$maxsize=5*1024*1024;
if($filesize>$maxsize)die("Error: File size is larger than the
allowed limit.");

// Verify MYME type of the file


if(in_array($filetype,$allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/".$filename)){
echo$filename." is already exists.";
}else{
move_uploaded_file($_FILES["photo"]["tmp_name"],"upload/".
$filename);
echo"Your file was uploaded successfully.";
}
}else{
echo"Error: There was a problem uploading your file. Please try
again.";
}
}else{
echo"Error: ".$_FILES["photo"]["error"];
}
}
?>

Note: The above script prevents uploading a file with the same name as an
existing file in the same folder. However, if you want to allow this just prepend
the file name with a random string or timestamp, like $filename = time() . '_' .
$_FILES["photo"]["name"];

You might be wondering what this code was all about. Well, let's go through
each part of this example code one by one for a better understanding of this
process.

Explanation of Code
Once the form is submitted information about the uploaded file can be accessed
via PHP superglobal array called $_FILES. For example, our upload form contains a
file select field called photo (i.e. name="photo"), if any user uploaded a file using this
field, we can obtains its details like the name, type, size, temporary name or any
error occurred while attempting the upload via the $_FILES["photo"] associative
array, like this:

 $_FILES["photo"]["name"] — This array value specifies the original name


of the file, including the file extension. It doesn't include the file path.
 $_FILES["photo"]["type"] — This array value specifies the MIME type of
the file.
 $_FILES["photo"]["size"] — This array value specifies the file size, in
bytes.
 $_FILES["photo"]["tmp_name"] — This array value specifies the temporary
name including full path that is assigned to the file once it has been uploaded to
the server.
 $_FILES["photo"]["error"] — This array value specifies error or status
code associated with the file upload, e.g. it will be 0, if there is no error.

The PHP code in the following example will simply display the details of the
uploaded file and stores it in a temporary directory on the web server.

Example
Download

<?php
if($_FILES["photo"]["error"]>0){
echo"Error: ".$_FILES["photo"]["error"]."<br>";
}else{
echo"File Name: ".$_FILES["photo"]["name"]."<br>";
echo"File Type: ".$_FILES["photo"]["type"]."<br>";
echo"File Size: ".($_FILES["photo"]["size"]/1024)." KB<br>";
echo"Stored in: ".$_FILES["photo"]["tmp_name"];
}
?>
Tip: Once a file has been successfully uploaded, it is automatically stored in a
temporary directory on the server. To store this file on a permanent basis, you
need to move it from the temporary directory to a permanent location using the
PHP's move_uploaded_file() function.
Chapter 23

PHP File Download
In this tutorial you will learn how to force download a file using PHP.

Downloading Files with PHP


Normally, you don't necessarily need to use any server side scripting language
like PHP to download images, zip files, pdf documents, exe files, etc. If such kind
of file is stored in a public accessible folder, you can just create a hyperlink
pointing to that file, and whenever a user click on the link, browser will
automatically downloads that file.

Example
Try this code »

<a href="downloads/test.zip">Download Zip file</a>


<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>
Clicking a link that points to a PDF or an Image file will not cause it to download
to your hard drive directly. It will only open the file in your browser. Further you
can save it to your hard drive. However, zip and exe files are downloaded
automatically to the hard drive by default.

Forcing a Download Using PHP


You can force images or other kind of files to download directly to the user's hard
drive using the PHP readfile() function. Here we're going to create a simple
image gallery that allows users to download the image files from the browser
with a single mouse click.

Let's create a file named "image-gallery.php" and place the following code inside
it.

Example
Run this code »

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
.img-box{
display: inline-block;
text-align: center;
margin: 0 15px;
}
</style>
</head>
<body>
<?php
// Array containing sample image file names
$images=array("kites.jpg","balloons.jpg");

// Loop through array to create image gallery


foreach($imagesas$image){
echo'<div class="img-box">';
echo'<img src="images/'.$image.'" width="200"
alt="'.pathinfo($image,PATHINFO_FILENAME).'">';
echo'<p><a href="download.php?
file='.urlencode($image).'">Download</a></p>';
echo'</div>';
}
?>
</body>
</html>
If you see the above example code carefully, you'll find the download link pints to
a "download.php" file, the URL also contains image file name as a query string.
Also, we've used PHP urlencode() function to encode the image file names so that
it can be safely passed as URL parameter, because file names may contain URL
unsafe characters.

Here's the complete code of "download.php" file, which force image download.

Example
Run this code »

<?php
if(isset($_REQUEST["file"])){
// Get parameters
$file=urldecode($_REQUEST["file"]);// Decode URL-encoded string

/* Test whether the file name contains illegal characters


such as "../" using the regular expression */
if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i',$file)){
$filepath="images/".$file;

// Process download
if(file_exists($filepath)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize($filepath));
flush();// Flush system output buffer
readfile($filepath);
die();
}else{
http_response_code(404);
die();
}
}else{
die("Invalid file name!");
}
}
?>

Similarly, you can force download other files formats like word doc, pdf files, etc.

The regular expression in the above example (line no-8) will simply not allow
those files whose name starts or ends with a dot character (.), for example, it
allows the file names such as kites.jpg or Kites.jpg, myscript.min.js but do not
allow kites.jpg. or .kites.jpg.

Please check out the tutorial on regular expressions to learn the regular
expressions in details.
Chapter 24

PHP Cookies
In this tutorial you will learn how to store a small amount of information within
the user's browser itself using the PHP cookies.

What is a Cookie
A cookie is a small text file that lets you store a small amount of data (nearly 4KB)
on the user's computer. They are typically used to keeping track of information
such as username that the site can retrieve to personalize the page when user
visit the website next time.

Tip: Each time the browser requests a page to the server, all the data in the
cookie is automatically sent to the server within the request.

Setting a Cookie in PHP


The setcookie() function is used to set a cookie in PHP. Make sure you call
the setcookie() function before any output generated by your script otherwise
cookie will not set. The basic syntax of this function can be given with:
setcookie(name, value, expire, path, domain, secure);

The parameters of the setcookie() function have the following meanings:

Paramete Description
r

name The name of the cookie.

value The value of the cookie. Do not store sensitive information


since this value is stored on the user's computer.
Paramete Description
r

expires The expiry date in UNIX timestamp format. After this time
cookie will become inaccessible. The default value is 0.

path Specify the path on the server for which the cookie will be
available. If set to /, the cookie will be available within the
entire domain.

domain Specify the domain for which the cookie is available to e.g
www.example.com.

secure This field, if present, indicates that the cookie should be sent
only if a secure HTTPS connection exists.

Tip: If the expiration time of the cookie is set to 0, or omitted, the cookie will
expire at the end of the session i.e. when the browser closes.

Here's an example that uses setcookie() function to create a cookie


named username and assign the value value John Carter to it. It also specify that the
cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec).

Example
Download

<?php
// Setting a cookie
setcookie("username","John Carter",time()+30*24*60*60);
?>
Note: All the arguments except the name are optional. You may also replace an
argument with an empty string ("") in order to skip that argument, however to
skip the expire argument use a zero (0) instead, since it is an integer.

Warning: Don't store sensitive data in cookies since it could potentially be


manipulated by the malicious user. To store the sensitive data securely
use sessions instead.
Accessing Cookies Values
The PHP $_COOKIE superglobal variable is used to retrieve a cookie value. It
typically an associative array that contains a list of all the cookies values sent by
the browser in the current request, keyed by cookie name. The individual cookie
value can be accessed using standard array notation, for example to display the
username cookie set in the previous example, you could use the following code.

Example
<?php
// Accessing an individual cookie value
echo $_COOKIE["username"];
?>
The PHP code in the above example produce the following output.

John Carter

It's a good practice to check whether a cookie is set or not before accessing its
value. To do this you can use the PHP isset() function, like this:

Example
Download

<?php
// Verifying whether a cookie is set or not
if(isset($_COOKIE["username"])){
echo"Hi ".$_COOKIE["username"];
}else{
echo"Welcome Guest!";
}
?>
You can use the print_r() function like print_r($_COOKIE); to see the structure of
this $_COOKIE associative array, like you with other arrays.
Removing Cookies
You can delete a cookie by calling the same setcookie() function with the cookie
name and any value (such as an empty string) however this time you need the set
the expiration date in the past, as shown in the example below:

Example
Download

<?php
// Deleting a cookie
setcookie("username","",time()-3600);
?>
Tip: You should pass exactly the same path, domain, and other arguments that
you have used when you first created the cookie in order to ensure that the
correct cookie is deleted.
Chapter 25

PHP Sessions
In this tutorial you will learn how to store certain data on the server on a
temporary basis using PHP session.

What is a Session
Although you can store data using cookies but it has some security issues. Since
cookies are stored on user's computer it is possible for an attacker to easily
modify a cookie content to insert potentially harmful data in your application that
might break your application.

Also every time the browser requests a URL to the server, all the cookie data for a
website is automatically sent to the server within the request. It means if you have
stored 5 cookies on user's system, each having 4KB in size, the browser needs to
upload 20KB of data each time the user views a page, which can affect your site's
performance.

You can solve both of these issues by using the PHP session. A PHP session stores
data on the server rather than user's computer. In a session based environment,
every user is identified through a unique number called session identifier or SID.
This unique session ID is used to link each user with their own information on the
server like emails, posts, etc.

Tip: The session IDs are randomly generated by the PHP engine which is almost
impossible to guess. Furthermore, because the session data is stored on the
server, it doesn't have to be sent with every browser request.

Starting a PHP Session


Before you can store any information in session variables, you must first start up
the session. To begin a new session, simply call the PHP session_start() function.
It will create a new session and generate a unique session ID for the user.

The PHP code in the example below simply starts a new session.

Example
Download

<?php
// Starting session
session_start();
?>
The session_start() function first checks to see if a session already exists by
looking for the presence of a session ID. If it finds one, i.e. if the session is already
started, it sets up the session variables and if doesn't, it starts a new session by
creating a new session ID.

Note: You must call the session_start() function at the beginning of the page i.e.


before any output generated by your script in the browser, much like you do
while setting the cookies with setcookie() function.

Storing and Accessing Session Data


You can store all your session data as key-value pairs in
the $_SESSION[] superglobal array. The stored data can be accessed during lifetime
of a session. Consider the following script, which creates a new session and
registers two session variables.

Example
Download

<?php
// Starting session
session_start();

// Storing session data


$_SESSION["firstname"]="Peter";
$_SESSION["lastname"]="Parker";
?>
To access the session data we set on our previous example from any other page
on the same web domain — simply recreate the session by
calling session_start() and then pass the corresponding key to
the $_SESSION associative array.

Example
Download

<?php
// Starting session
session_start();

// Accessing session data


echo'Hi, '.$_SESSION["firstname"].' '.$_SESSION["lastname"];
?>
The PHP code in the example above produce the following output.

Hi, Peter Parker

Note: To access the session data in the same page there is no need to recreate
the session since it has been already started on the top of the page.

Destroying a Session
If you want to remove certain session data, simply unset the corresponding key
of the $_SESSION associative array, as shown in the following example:

Example
Download

<?php
// Starting session
session_start();

// Removing session data


if(isset($_SESSION["lastname"])){
unset($_SESSION["lastname"]);
}
?>
However, to destroy a session completely, simply call
the session_destroy() function. This function does not need any argument and a
single call destroys all the session data.

Example
Download

<?php
// Starting session
session_start();

// Destroying session
session_destroy();
?>
Note: Before destroying a session with the session_destroy() function, you need to
first recreate the session environment if it is not already there using
the session_start() function, so that there is something to destroy.

Every PHP session has a timeout value — a duration, measured in seconds —


which determines how long a session should remain alive in the absence of any
user activity. You can adjust this timeout duration by changing the value
of session.gc_maxlifetime variable in the PHP configuration file (php.ini).
Chapter 26

PHP Send Emails
In this tutorial you will learn how to send simple text or HTML emails directly
from the script using the PHP mail() function.

The PHP mail() Function
Sending email messages are very common for a web application, for example,
sending welcome email when a user create an account on your website, sending
newsletters to your registered users, or getting user feedback or comment
through website's contact form, and so on.

You can use the PHP built-in mail() function for creating and sending email
messages to one or more recipients dynamically from your PHP application either
in a plain-text form or formatted HTML. The basic syntax of this function can be
given with:
mail(to, subject, message, headers, parameters)

The following table summarizes the parameters of this function.

Parameter Description

Required — The following parameters are required

to The recipient's email address.

subject Subject of the email to be sent. This parameter i.e. the


subject line cannot contain any newline character (\n).

message Defines the message to be sent. Each line should be


separated with a line feed-LF (\n). Lines should not
Parameter Description

exceed 70 characters.

Optional — The following parameters are optional

headers This is typically used to add extra headers such as "From",


"Cc", "Bcc". The additional headers should be separated
with a carriage return plus a line feed-CRLF (\r\n).

parameters Used to pass additional parameters.

Sending Plain Text Emails


The simplest way to send an email with PHP is to send a text email. In the
example below we first declare the variables — recipient's email address, subject
line and message body — then we pass these variables to the mail() function to
send the email.

Example
Download

<?php
$to='[email protected]';
$subject='Marriage Proposal';
$message='Hi Jane, will you marry me?';
$from='[email protected]';

// Sending email
if(mail($to,$subject,$message)){
echo'Your mail has been sent successfully.';
}else{
echo'Unable to send email. Please try again.';
}
?>
Sending HTML Formatted Emails
When you send a text message using PHP, all the content will be treated as
simple text. We're going to improve that output, and make the email into a
HTML-formatted email.

To send an HTML email, the process will be the same. However, this time we need
to provide additional headers as well as an HTML formatted message.

Example
Download

<?php
$to='[email protected]';
$subject='Marriage Proposal';
$from='[email protected]';

// To send HTML mail, the Content-type header must be set


$headers='MIME-Version: 1.0'."\r\n";
$headers.='Content-type: text/html; charset=iso-8859-1'."\r\n";

// Create email headers


$headers.='From: '.$from."\r\n".
'Reply-To: '.$from."\r\n".
'X-Mailer: PHP/'.phpversion();

// Compose a simple HTML email message


$message='<html><body>';
$message.='<h1 style="color:#f40;">Hi Jane!</h1>';
$message.='<p style="color:#080;font-size:18px;">Will you marry
me?</p>';
$message.='</body></html>';

// Sending email
if(mail($to,$subject,$message,$headers)){
echo'Your mail has been sent successfully.';
}else{
echo'Unable to send email. Please try again.';
}
?>
Note: However, the PHP mail() function is a part of the PHP core but you need to
set up a mail server on your machine to make it really work.

In the next two chapters (PHP Form Handling and PHP Form Validation) you will
learn how to implement an interactive contact form on your website to receive
the user's comment and feedback through emails using this PHP send mail
feature.
Chapter 27

PHP Form Handling
In this tutorial you'll learn how to collect user inputs submitted through a form
using the PHP superglobal variables $_GET, $_POST and $_REQUEST.

Creating a Simple Contact Form


In this tutorial we are going to create a simple HMTL contact form that allows
users to enter their comment and feedback then displays it to the browser using
PHP.

Open up your favorite code editor and create a new PHP file. Now type the
following code and save this file as "contact-form.php" in the root directory of
your project.

Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php"method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text"name="name"id="inputName">
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text"name="email"id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text"name="subject"id="inputSubject">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea
name="message"id="inputComment"rows="5"cols="30"></textarea>
</p>
<input type="submit"value="Submit">
<input type="reset"value="Reset">
</form>
</body>
</html>

Explanation of code
Notice that there are two attributes within the opening <form> tag:

 The action attribute references a PHP file "process-form.php" that receives


the data entered into the form when user submit it by pressing the submit
button.
 The method attribute tells the browser to send the form data through POST
method.

Rest of the elements inside the form are basic form controls to receive user
inputs. To learn more about HTML form elements please check out the HTML
Forms tutorial.

Capturing Form Data with PHP


To access the value of a particular form field, you can use the following
superglobal variables. These variables are available in all scopes throughout a
script.
Supergloba Description
l
$_GET Contains a list of all the field names and values sent by a
form using the get method (i.e. via the URL parameters).
$_POST Contains a list of all the field names and values sent by a
form using the post method (data will not visible in the
URL).
$_REQUEST Contains the values of both the $_GET and $_POST variables
as well as the values of the $_COOKIE superglobal variable.
When a user submit the above contact form through clicking the submit button,
the form data is sent to the "process-form.php" file on the server for processing.
It simply captures the information submitted by the user and displays it to
browser.

The PHP code of "process-form.php" file will look something like this:

Example
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em><?phpecho$_POST["name"]?></li>
<li><em>Email:</em><?phpecho$_POST["email"]?></li>
<li><em>Subject:</em><?phpecho$_POST["subject"]?></li>
<li><em>Message:</em><?phpecho$_POST["message"]?></li>
</ol>
</body>
</html>

The PHP code above is quite simple. Since the form data is sent through the post
method, you can retrieve the value of a particular form field by passing its name
to the $_POST superglobal array, and displays each field value
using echo() statement.
In real world you cannot trust the user inputs; you must implement some sort of
validation to filter the user inputs before using them. In the next chapter you will
learn how sanitize and validate this contact form data and send it through the
email using PHP.

Chapter 28

PHP Form Validation
In this tutorial you'll learn how to sanitize and validate form data using PHP
filters.

Sanitizing and Validating Form Data


As you have seen in the previous tutorial, the process of capturing and displaying
the submitted form data is quite simple. In this tutorial you will learn how to
implement a simple contact form on your website that allows the user to send
their comment and feedback through email. We will use the
same PHP mail() function to send the emails.

We are also going to implement some basic security feature like sanitization and
validation of the user's input so that user can not insert potentially harmful data
that compromise the website security or might break the application.

The following is our all-in-one PHP script which does the following things:

 It will ask the users to enter his comments about the website.
 The same script displays the contact form and process the submitted form
data.
 The script sanitizes and validates the user inputs. If any required field
(marked with *) is missing or validation failed due to incorrect inputs the script
redisplays the form with an error message for corresponding form field.
 The script remembers which fields the user has already filled in, and prefills
those fields when the form redisplayed due to validation error.
 If the data submitted by the user are acceptable and everything goes well it
will send an email to the website administrator and display a success message to
the user.

Type the following code in "contact.php" file and save in your project root
directory:

Example
Download
<?php
// Functions to filter user inputs
functionfilterName($field){
// Sanitize user name
$field=filter_var(trim($field),FILTER_SANITIZE_STRING);

// Validate user name


if(filter_var($field,FILTER_VALIDATE_REGEXP,array("options"=>arra
y("regexp"=>"/^[a-zA-Z\s]+$/")))){
return$field;
}else{
returnFALSE;
}
}
functionfilterEmail($field){
// Sanitize e-mail address
$field=filter_var(trim($field),FILTER_SANITIZE_EMAIL);

// Validate e-mail address


if(filter_var($field,FILTER_VALIDATE_EMAIL)){
return$field;
}else{
returnFALSE;
}
}
functionfilterString($field){
// Sanitize string
$field=filter_var(trim($field),FILTER_SANITIZE_STRING);
if(!empty($field)){
return$field;
}else{
returnFALSE;
}
}

// Define variables and initialize with empty values


$nameErr=$emailErr=$messageErr="";
$name=$email=$subject=$message="";

// Processing form data when form is submitted


if($_SERVER["REQUEST_METHOD"]=="POST"){

// Validate user name


if(empty($_POST["name"])){
$nameErr="Please enter your name.";
}else{
$name=filterName($_POST["name"]);
if($name==FALSE){
$nameErr="Please enter a valid name.";
}
}

// Validate email address


if(empty($_POST["email"])){
$emailErr="Please enter your email address.";
}else{
$email=filterEmail($_POST["email"]);
if($email==FALSE){
$emailErr="Please enter a valid email address.";
}
}

// Validate message subject


if(empty($_POST["subject"])){
$subject="";
}else{
$subject=filterString($_POST["subject"]);
}

// Validate user comment


if(empty($_POST["message"])){
$messageErr="Please enter your comment.";
}else{
$message=filterString($_POST["message"]);
if($message==FALSE){
$messageErr="Please enter a valid comment.";
}
}

// Check input errors before sending email


if(empty($nameErr)&&empty($emailErr)&&empty($messageErr)){
// Recipient email address
$to='[email protected]';

// Create email headers


$headers='From: '.$email."\r\n".
'Reply-To: '.$email."\r\n".
'X-Mailer: PHP/'.phpversion();

// Sending email
if(mail($to,$subject,$message,$headers)){
echo'<p class="success">Your message has been sent successfully!
</p>';
}else{
echo'<p class="error">Unable to send email. Please try again!
</p>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<style type="text/css">
.error{color: red;}
.success{color: green;}
</style>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="contact.php"method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text"name="name"id="inputName"value="<?php echo
$name;?>">
<span class="error"><?phpecho$nameErr;?></span>
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text"name="email"id="inputEmail"value="<?php echo
$email;?>">
<span class="error"><?phpecho$emailErr;?></span>
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text"name="subject"id="inputSubject"value="<?php
echo $subject;?>">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message"id="inputComment"rows="5"cols="30"><?
phpecho$message;?></textarea>
<span class="error"><?phpecho$messageErr;?></span>
</p>
<input type="submit"value="Send">
<input type="reset"value="Reset">
</form>
</body>
</html>

Explanation of code
You might think what that code was all about. OK, let's get straight into it.

 The filterName() function (line no-03) validate input value as person's name.


A valid name can only contain alphabetical characters (a-z, A-Z).
 The filterEmail() function (line no-14) validate input value as email address.
 The filterString() function (line no-25) only sanitize the input value by
stripping HTML tags and special characters. It doesn't validate the input value 
against anything.
 The attribute action="contact.php" (line no-111) inside the <form> tag
specifies that the same contact.php file display the form as well as process the
form data.
 The PHP code inside the value attribute of <input> and <textarea> e.g. <?php
echo $name; ?> display prefilled value when form is redisplayed upon validation
error.
 The PHP code inside the .error class e.g. <span class="error"><?php echo
$nameErr; ?></span> display error for corresponding field.
Rest the thing we have already covered in previous chapters. To learn more about
sanitize and validate filters, please check out the PHP Filter reference.

Note: You need to setup a mail server on your machine for the


PHP mail() function to work. If you just want to implement the form validation
you can replace the mail part (line no. 81 to 94) with your own custom code.

Chapter 29

PHP Filters
In this tutorial you will learn how to sanitize and validate user inputs in PHP.

Validating and Sanitizing Data with Filters


Sanitizing and validating user input is one of the most common tasks in a web
application. To make this task easier PHP provides native filter extension that you
can use to sanitize or validate data such as e-mail addresses, URLs, IP addresses,
etc.
To validate data using filter extension you need to use the
PHP's filter_var() function. The basic syntax of this function can be given with:
filter_var(variable, filter, options)

This function takes three parameters out of which the last two are optional. The
first parameter is the value to be filtered, the second parameter is the ID of the
filter to apply, and the third parameter is the array of options related to filter.
Let's see how it works.

Sanitize a String
The following example will sanitize a string by removing all HTML tags from it:

Example
Run this code »

<?php
// Sample user comment
$comment="<h1>Hey there! How are you doing today?</h1>";

// Sanitize and print comment string


$sanitizedComment=filter_var($comment,FILTER_SANITIZE_STRING);
echo$sanitizedComment;
?>
The output of the above example will look something like this:

Hey there! How are you doing today?

Validate Integer Values


The following example will validate whether the value is a valid integer or not.

Example
Run this code »

<?php
// Sample integer value
$int=20;

// Validate sample integer value


if(filter_var($int,FILTER_VALIDATE_INT)){
echo"The <b>$int</b> is a valid integer";
}else{
echo"The <b>$int</b> is not a valid integer";
}
?>
In the above example, if variable $int is set to 0, the example code will display
invalid integer message. To fix this problem, you need to explicitly test for the
value 0, as follow:

Example
Run this code »

<?php
// Sample integer value
$int=0;

// Validate sample integer value


if(filter_var($int,FILTER_VALIDATE_INT)===0||
filter_var($int,FILTER_VALIDATE_INT)){
echo"The <b>$int</b> is a valid integer";
}else{
echo"The <b>$int</b> is not a valid integer";
}
?>

Validate IP Addresses
The following example will validate whether the value is a valid IP address or not.

Example
Run this code »

<?php
// Sample IP address
$ip="172.16.254.1";
// Validate sample IP address
if(filter_var($ip,FILTER_VALIDATE_IP)){
echo"The <b>$ip</b> is a valid IP address";
}else{
echo"The <b>$ip</b> is not a valid IP address";
}
?>
You can further apply validation for IPV4 or IPV6 IP addresses by using
the FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 flags, respectively. Here's an example:

Example
Run this code »

<?php
// Sample IP address
$ip="172.16.254.1";

// Validate sample IP address


if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_IPV6)){
echo"The <b>$ip</b> is a valid IPV6 address";
}else{
echo"The <b>$ip</b> is not a valid IPV6 address";
}
?>

Sanitize and Validate Email Addresses


The following example will show you how to sanitize and validate an e-mail
address.

Example
Run this code »

<?php
// Sample email address
$email="someone@@example.com";

// Remove all illegal characters from email


$sanitizedEmail=filter_var($email,FILTER_SANITIZE_EMAIL);
// Validate email address
if($email==$sanitizedEmail&&filter_var($email,FILTER_VALIDATE_EMA
IL)){
echo"The $email is a valid email address";
}else{
echo"The $email is not a valid email address";
}
?>
Note: The FILTER_SANITIZE_EMAIL filter removes all invalid characters from the
provided email address string except letters, digits and !#$%&'*+-=?^_`{|}~@.[].

Sanitize and Validate URLs


The following example will show you how to sanitize and validate a url.

Example
Run this code »

<?php
// Sample website url
$url="http:://www.example.com";

// Remove all illegal characters from url


$sanitizedUrl=filter_var($url,FILTER_SANITIZE_URL);

// Validate website url


if($url==$sanitizedUrl&&filter_var($url,FILTER_VALIDATE_URL)){
echo"The $url is a valid website url";
}else{
echo"The $url is not a valid website url";
}
?>
Note: The FILTER_SANITIZE_URL filter removes all invalid characters from the
provided URL string except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.

You can also check whether a URL contains query string or not by using the
flag FILTER_FLAG_QUERY_REQUIRED, as shown in the following example:

Example
Run this code »

<?php
// Sample website url
$url="http://www.example.com?topic=filters";

// Validate website url for query string


if(filter_var($url,FILTER_VALIDATE_URL,FILTER_FLAG_QUERY_REQUIRED
)){
echo"The <b>$url</b> contains query string";
}else{
echo"The <b>$url</b> does not contain query string";
}
?>
See the tutorial on HTML URL to learn about the different components of a URL.

Validate Integers Within a Range


The following example will validate whether the supplied value is an integer or
not, as well as whether it lies within the range of 0 to 100 or not.

Example
Run this code »

<?php
// Sample integer value
$int=75;

// Validate sample integer value


if(filter_var($int,FILTER_VALIDATE_INT,array("options"=>array("mi
n_range"=>0,"max_range"=>100)))){
echo"The <b>$int</b> is within the range of 0 to 100";
}else{
echo"The <b>$int</b> is not within the range of 0 to 100";
}
?>
Chapter 30

PHP Error Handling
In this tutorial you will learn how to use the PHP's error handling functions to
deal with the error conditions gracefully.

Handling Errors
Sometimes your application will not run as it supposed to do, resulting in an
error. There are a number of reasons that may cause errors, for example:
 The Web server might run out of disk space
 A user might have entered an invalid value in a form field
 The file or database record that you were trying to access may not exist
 The application might not have permission to write to a file on the disk
 A service that the application needs to access might be temporarily
unavailable

These types of errors are known as runtime errors, because they occur at the time
the script runs. They are distinct from syntax errors that need to be fixed before
the script will run.

A professional application must have the capabilities to handle such runtime


error gracefully. Usually this means informing the user about the problem more
clearly and precisely.

Understanding Error Levels


Usually, when there's a problem that prevents a script from running properly, the
PHP engine triggers an error. Each error is represented by an integer value and
an associated constant. The following table list some of the common error levels:

Error Level Value Description

E_ERROR 1 A fatal run-time error, that can't be


recovered from. The execution of the script
is stopped immediately.

E_WARNING 2 A run-time warning. It is non-fatal and most


errors tend to fall into this category. The
execution of the script is not stopped.

E_NOTICE 8 A run-time notice. Indicate that the script


encountered something that could possibly
an error, although the situation could also
occur when running a script normally.

E_USER_ERROR 256 A fatal user-generated error message. This is


like an E_ERROR, except it is generated by
the PHP script using the
function trigger_error() rather than
the PHP engine.

E_USER_WARNIN 512 A non-fatal user-generated warning


G message. This is like an E_WARNING, except
it is generated by the PHP script using the
function trigger_error() rather than
the PHP. engine

E_USER_NOTICE 1024 A user-generated notice message. This is like


an E_NOTICE, except it is generated by the
PHP script using the
function trigger_error() rather than
the PHP engine.

E_STRICT 2048 Not strictly an error, but triggered whenever


PHP encounters code that could lead to
problems or forward incompatibilities

E_ALL 8191 All errors and warnings, except


of E_STRICT prior to PHP 5.4.0.

For more error levels, please check out the reference on PHP Error Levels.

The PHP engine triggers an error whenever it encounters a problem with your
script, but you can also trigger errors yourself to generate more user friendly
error messages. This way you can make your application more sofisticated. The
following section describes some of common methods used for handling errors
in PHP:

Basic Error Handling Using the die() Function


Consider the following example that simply tries to open a text file for reading
only.

Example
Download

<?php
// Try to open a non-existent file
$file=fopen("sample.txt","r");
?>
If the file does not exist you might get an error like this:

Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file


or directory in C:\wamp\www\project\test.php on line 2

If we follow some simple steps we can prevent the users from getting such error
message.

Example
Download

<?php
if(file_exists("sample.txt")){
$file=fopen("sample.txt","r");
}else{
die("Error: The file you are trying to access doesn't exist.");
}
?>
Now if you run the above script you will get the error message like this:

Error: The file you are trying to access doesn't exist.

As you can see by implementing a simple check whether the file exist or not
before trying to access it, we can generate an error message that is more
meaningful to the user.

The die() function used above simply display the custom error message and
terminate the current script if 'sample.txt' file is not found.

Creating a Custom Error Handler


You can create your own error handler function to deal with the run-time error
generated by PHP engine. The custom error handler provides you greater
flexibility and better control over the errors, it can inspect the error and decide
what to do with the error, it might display a message to the user, log the error in
a file or database or send by e-mail, attempt to fix the problem and carry on, exit
the execution of the script or ignore the error altogether.

The custom error handler function must be able to handle at least two
parameters (errno and errstr), however it can optionally accept an additional
three parameters (errfile, errline, and errcontext), as described below:

Parameter Description

Required — The following parameters are required

errno Specifies the level of the error, as an integer. This


corresponds to the appropriate error level constant
( E_ERROR, E_WARNING, and so on)

errstr Specifies the error message as a string

Optional — The following parameters are optional

errfile Specifies the filename of the script file in which the error
occurred, as a string

errline Specifies the line number on which the error occurred, as a


string

errcontext Specifies an array containing all the variables and their


values that existed at the time the error occurred. Useful for
debugging

Here's an example of a simple custom error handling function. This


handler, customError() is triggered whenever an error occurred, no matter how
trivial. It then outputs the details of the error to the browser and stops the
execution of the script.

Example
Download

<?php
// Error handler function
functioncustomError($errno,$errstr){
echo"<b>Error:</b> [$errno] $errstr";
}
?>
You need to tell the PHP to use your custom error handler function — just call
the built-in set_error_handler() function, passing in the name of the function.

Example
Download

<?php
// Error handler function
functioncustomError($errno,$errstr){
echo"<b>Error:</b> [$errno] $errstr";
}

// Set error handler


set_error_handler("customError");

// Trigger error
echo($test);
?>

Error Logging
Log Error Messages in a Text File
You can also logs details of the error to the log file, like this:

Example
Download

<?php
functioncalcDivision($dividend,$divisor){
if($divisor==0){
trigger_error("calcDivision(): The divisor cannot be
zero",E_USER_WARNING);
returnfalse;
}else{
return($dividend/$divisor);
}
}
functioncustomError($errno,$errstr,$errfile,$errline,$errcontext)
{
$message=date("Y-m-d H:i:s - ");
$message.="Error: [".$errno."], "."$errstr in $errfile on line
$errline, ";
$message.="Variables:".print_r($errcontext,true)."\r\n";

error_log($message,3,"logs/app_errors.log");
die("There was a problem, please try again.");
}
set_error_handler("customError");
echocalcDivision(10,0);
echo"This will never be printed.";
?>

Send Error Messages by E-Mail


You can also send e-mail with the error details using the
same error_log() function.

Example
Download

<?php
functioncalcDivision($dividend,$divisor){
if($divisor==0){
trigger_error("calcDivision(): The divisor cannot be
zero",E_USER_WARNING);
returnfalse;
}else{
return($dividend/$divisor);
}
}
functioncustomError($errno,$errstr,$errfile,$errline,$errcontext)
{
$message=date("Y-m-d H:i:s - ");
$message.="Error: [".$errno."], "."$errstr in $errfile on line
$errline, ";
$message.="Variables:".print_r($errcontext,true)."\r\n";

error_log($message,1,"[email protected]");
die("There was a problem, please try again. Error report
submitted to webmaster.");
}
set_error_handler("customError");
echocalcDivision(10,0);
echo"This will never be printed.";
?>

Trigger an Error
Although the PHP engine triggers an error whenever it encounters a problem
with your script, however you can also trigger errors yourself. This can help to
make your application more robust, because it can flag potential problems before
they turn into serious errors.

To trigger an error from within your script, call the trigger_error() function,


passing in the error message that you want to generate:
trigger_error("There was a problem.");

Consider the following function that calculates division of the two numbers.

Example
Download

<?php
functioncalcDivision($dividend,$divisor){
return($dividend/$divisor);
}

// Calling the function


echocalcDivision(10,0);
?>
If a value of zero (0) is passed as the $divisor parameter, the error generated by
the PHP engine will look something like this:

Warning: Division by zero in C:\wamp\www\project\test.php on line 3

This message doesn't look very informative. Consider the following example that
uses the trigger_error() function to generate the error.

Example
Download
<?php
functioncalcDivision($dividend,$divisor){
if($divisor==0){
trigger_error("The divisor cannot be zero",E_USER_WARNING);
returnfalse;
}else{
return($dividend/$divisor);
}
}

// Calling the function


echocalcDivision(10,0);
?>
Now the script generates this error message:

Warning: The divisor cannot be zero in C:\wamp\www\project\error.php on line 4

As you can see the error message generated by the second example explains the
problem more clearly as compared to the previous one.
Chapter 31

PHP Classes and Objects
In this tutorial you will learn how to write code in object-oriented style in PHP.

What is Object Oriented Programming


Object-Oriented Programming (OOP) is a programming model that is based on
the concept of classes and objects. As opposed to procedural programming
where the focus is on writing procedures or functions that perform operations on
the data, in object-oriented programming the focus is on the creations of objects
which contain both data and functions together.

Object-oriented programming has several advantages over conventional or


procedural style of programming. The most important ones are listed below:

 It provides a clear modular structure for the programs.


 It helps you adhere to the "don't repeat yourself" (DRY) principle, and thus
make your code much easier to maintain, modify and debug.
 It makes it possible to create more complicated behavior with less code
and shorter development time and high degree of reusability.

The following sections will describe how classes and objects work in PHP.
Tip: The idea behind Don't Repeat Yourself (DRY) principle is reducing the
repetition of code by abstracting out the code that are common for the
application and placing them at a single place and reuse them instead of
repeating it.

Understanding Classes and Objects


Classes and objects are the two main aspects of object-oriented programming. A
class is a self-contained, independent collection of variables and functions which
work together to perform one or more specific tasks, while objects are individual
instances of a class.

A class acts as a template or blueprint from which lots of individual objects can
be created. When individual objects are created, they inherit the same generic
properties and behaviors, although each object may have different values for
certain properties.

For example, think of a class as a blueprint for a house. The blueprint itself is not
a house, but is a detailed plan of the house. While, an object is like an actual
house built according to that blueprint. We can build several identical houses
from the same blueprint, but each house may have different paints, interiors and
families inside, as shown in the illustration below.

A class can be declared using the class keyword, followed by the name of the


class and a pair of curly braces ({}), as shown in the following example.
Let's create a PHP file named Rectangle.php and put the following example code
inside it so that our class code should be separated from rest of the program. We
can then use it wherever it's needed by simply including the Rectangle.php file.

Example
Download
<?php
classRectangle
{
// Declare properties
public$length=0;
public$width=0;

// Method to get the perimeter


publicfunctiongetPerimeter(){
return(2*($this->length+$this->width));
}

// Method to get the area


publicfunctiongetArea(){
return($this->length*$this->width);
}
}
?>

The public keyword before the properties and methods in the example above, is


an access modifier, which indicates that this property or method is accessible
from anywhere. We will learn more about this a little later in this chapter.

Note: Syntactically, variables within a class are called properties, whereas


functions are called methods. Also class names conventionally are written in
PascalCase i.e. each concatenated word starts with an uppercase letter (e.g.
MyClass).

Once a class has been defined, objects can be created from the class with
the new keyword. Class methods and properties can directly be accessed through
this object instance.

Create another PHP file name test.php and put the following code inside it.

Example
Run this code »
<?php
// Include class definition
require"Rectangle.php";

// Create a new object from Rectangle class


$obj=newRectangle;

// Get the object properties values


echo$obj->length;// 0utput: 0
echo$obj->width;// 0utput: 0

// Set object properties values


$obj->length=30;
$obj->width=20;

// Read the object properties values again to show the change


echo$obj->length;// 0utput: 30
echo$obj->width;// 0utput: 20

// Call the object methods


echo$obj->getPerimeter();// 0utput: 100
echo$obj->getArea();// Output: 600
?>

The arrow symbol (->) is an OOP construct that is used to access contained
properties and methods of a given object. Whereas, the pseudo-
variable $this provides a reference to the calling object i.e. the object to which
the method belongs.

The real power of object oriented programming becomes evident when using
multiple instances of the same class, as shown in the following example:

Example
Run this code »
<?php
// Include class definition
require"Rectangle.php";

// Create multiple objects from the Rectangle class


$obj1=newRectangle;
$obj2=newRectangle;

// Call the methods of both the objects


echo$obj1->getArea();// Output: 0
echo$obj2->getArea();// Output: 0
// Set $obj1 properties values
$obj1->length=30;
$obj1->width=20;

// Set $obj2 properties values


$obj2->length=35;
$obj2->width=50;

// Call the methods of both the objects again


echo$obj1->getArea();// Output: 600
echo$obj2->getArea();// Output: 1750
?>

As you can see in the above example, calling the getArea() method on different


objects causes that method to operate on a different set of data. Each object
instance is completely independent, with its own properties and methods, and
thus can be manipulated independently, even if they're of the same class.

Using Constructors and Destructors


To make the object-oriented programming easier, PHP provides some magic
methods that are executed automatically when certain actions occur within an
object.

For example, the magic method __construct() (known as constructor) is executed


automatically whenever a new object is created. Similarly, the magic
method __destruct() (known as destructor) is executed automatically when the
object is destroyed. A destructor function cleans up any resources allocated to an
object once the object is destroyed.

Example
Run this code »
<?php
classMyClass
{
// Constructor
publicfunction__construct(){
echo'The class "'.__CLASS__.'" was initiated!<br>';
}

// Destructor
publicfunction__destruct(){
echo'The class "'.__CLASS__.'" was destroyed.<br>';
}
}

// Create a new object


$obj=newMyClass;

// Output a message at the end of the file


echo"The end of the file is reached.";
?>

The PHP code in the above example will produce the following output:

The class "MyClass" was initiated!


The end of the file is reached.
The class "MyClass" was destroyed.
A destructor is called automatically when a scripts ends. However, to explicitly
trigger the destructor, you can destroy the object using the PHP unset() function,
as follow:

Example
Run this code »
<?php
classMyClass
{
// Constructor
publicfunction__construct(){
echo'The class "'.__CLASS__.'" was initiated!<br>';
}

// Destructor
publicfunction__destruct(){
echo'The class "'.__CLASS__.'" was destroyed.<br>';
}
}

// Create a new object


$obj=newMyClass;

// Destroy the object


unset($obj);

// Output a message at the end of the file


echo"The end of the file is reached.";
?>

Now, the PHP code in the above example will produce the following output:

The class "MyClass" was initiated!


The class "MyClass" was destroyed.
The end of the file is reached.
Tip: PHP automatically clean up all resources allocated during execution when
the script is finished, e.g. closing database connections, destroying objects, etc.

Note: The __CLASS__ is a magic constant which contains the name of the class in


which it is occur. It is empty, if it occurs outside of the class.

Extending Classes through Inheritance


Classes can inherit the properties and methods of another class using
the extends keyword. This process of extensibility is called inheritance. It is
probably the most powerful reason behind using the object-oriented
programming model.

Example
Run this code »
<?php
// Include class definition
require"Rectangle.php";

// Define a new class based on an existing class


classSquareextendsRectangle
{
// Method to test if the rectangle is also a square
publicfunctionisSquare(){
if($this->length==$this->width){
returntrue;// Square
}else{
returnfalse;// Not a square
}
}
}

// Create a new object from Square class


$obj=newSquare;

// Set object properties values


$obj->length=20;
$obj->width=20;

// Call the object methods


if($obj->isSquare()){
echo"The area of the square is ";
}else{
echo"The area of the rectangle is ";
};
echo$obj->getArea();
?>

The PHP code in the above example will produce the following output:

The area of the square is 400


As you can see in the above example, even though the class definition of Square
doesn't explicitly contain getArea() method nor the $length and $width property,
instances of the Square class can use them, as they inherited from the parent
Rectangle class.

Tip: Since a child class is derived from a parent class, it is also referred to as a


derived class, and its parent is called the base class.

Controlling the Visibility of Properties and Methods


When working with classes, you can even restrict access to its properties and
methods using the visibility keywords for greater control. There are three visibility
keywords (from most visible to least visible): public, protected, private, which
determines how and from where properties and methods can be accessed and
modified.
 public — A public property or method can be accessed anywhere, from
within the class and outside. This is the default visibility for all class members in
PHP.
 protected — A protected property or method can only be accessed from
within the class itself or in child or inherited classes i.e. classes that extends that
class.
 private — A private property or method is accessible only from within the
class that defines it. Even child or inherited classes cannot access private
properties or methods.

The following example will show you how this visibility actually works:

Example
Download
<?php
// Class definition
classAutomobile
{
// Declare properties
public$fuel;
protected$engine;
private$transmission;
}
classCarextendsAutomobile
{
// Constructor
publicfunction__construct(){
echo'The class "'.__CLASS__.'" was initiated!<br>';
}
}

// Create an object from Automobile class


$automobile=newAutomobile;

// Attempt to set $automobile object properties


$automobile->fuel='Petrol';// ok
$automobile->engine='1500 cc';// fatal error
$automobile->transmission='Manual';// fatal error

// Create an object from Car class


$car=newCar;

// Attempt to set $car object properties


$car->fuel='Diesel';// ok
$car->engine='2200 cc';// fatal error
$car->transmission='Automatic';// undefined
?>

Static Properties and Methods


In addition to the visibility, properties and methods can also be declared
as static, which makes them accessible without needing an instantiation of the
class. Static properties and methods can be accessed using the scope resolution
operator (::), like this: ClassName::$property and ClassName::method().

A property declared as static cannot be accessed via the object of that class
though a static method can be, as demonstrated in the following example:

Example
Download
<?php
// Class definition
classHelloClass
{
// Declare a static property
publicstatic$greeting="Hello World!";

// Declare a static method


publicstaticfunctionsayHello(){
echo self::$greeting;
}
}
// Attempt to access static property and method directly
echo HelloClass::$greeting;// Output: Hello World!
HelloClass::sayHello();// Output: Hello World!

// Attempt to access static property and method via object


$hello=newHelloClass;
echo$hello->greeting;// Strict Warning
$hello->sayHello();// Output: Hello World!
?>
The keyword self in the above example means "the current class". It is never
preceded by a dollar sign ($) and always followed by the :: operator (e.g. self::
$name).

The self keyword is different from the this keyword which means "the current


object" or  "the current instance of a class". The this keyword is always preceded
by a dollar sign ($) and followed by the -> operator (e.g. $this->name).

Note: Since static methods can be called without an instance of a class (i.e.


object), the pseudo-variable $this is not available inside the method declared as
static.

We hope you've understood the basic concepts of object-oriented programming


by now. You'll find more examples on OOP in PHP and MySQL database section.

Chapter 32

PHP Magic Constants
In this tutorial you will learn how to work with PHP magic constants.

What is Magic Constants


In the PHP constants chapter we've learned how to define and use constants in
PHP script.

PHP moreover also provide a set of special predefined constants that change
depending on where they are used. These constants are called magic constants.
For example, the value of __LINE__ depends on the line that it's used on in your
script.
Magic constants begin with two underscores and end with two underscores. The
following section describes some of the most useful magical PHP constants.

__LINE__
The __LINE__ constant returns the current line number of the file, like this:

Example
Run this code »

<?php
echo"Line number ".__LINE__."<br>";// Displays: Line number 2
echo"Line number ".__LINE__."<br>";// Displays: Line number 3
echo"Line number ".__LINE__."<br>";// Displays: Line number 4
?><?php

__FILE__
The __FILE__ constant returns full path and name of the PHP file that's being
executed. If used inside an include, the name of the included file is returned.

Example
Download

<?php
// Displays the absolute path of this file
echo"The full path of this file is: ".__FILE__;
?>

__DIR__
The __DIR__ constant returns the directory of the file. If used inside an include, the
directory of the included file is returned. Here's an example:

Example
Download

<?php
// Displays the directory of this file
echo"The directory of this file is: ".__DIR__;
?>
__FUNCTION__
The __FUNCTION__ constant returns the name of the current function.

Example
Run this code »

<?php
functionmyFunction(){
echo"The function name is - ".__FUNCTION__;
}
myFunction();// Displays: The function name is - myFunction
?>

__CLASS__
The __CLASS__ constant returns the name of the current class. Here's an example:

Example
Run this code »

<?php
classMyClass
{
publicfunctiongetClassName(){
return__CLASS__;
}
}
$obj=newMyClass();
echo$obj->getClassName();// Displays: MyClass
?>

__METHOD__
The __METHOD__ constant returns the name of the current class method.

Example
Run this code »

<?php
classSample
{
publicfunctionmyMethod(){
echo__METHOD__;
}
}
$obj=newSample();
$obj->myMethod();// Displays: Sample::myMethod
?>

__NAMESPACE__
The __NAMESPACE__ constant returns the name of the current namespace.

Example
Download

<?php
namespace MyNamespace;
classMyClass
{
publicfunctiongetNamespace(){
return__NAMESPACE__;
}
}
$obj=newMyClass();
echo$obj->getNamespace();// Displays: MyNamespace
?>
Chapter 33

PHP JSON Parsing
In this tutorial you will learn how to encode and decode JSON data in PHP.

What is JSON
JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-
interchange format which is quick and easy to parse and generate.

JSON, like XML, is a text-based format that's easy to write and easy to understand
for both humans and computers, but unlike XML, JSON data structures occupy
less bandwidth than their XML versions. JSON is based on two basic structures:

 Object: This is defined as a collection of key/value pairs (i.e. key:value). Each


object begins with a left curly bracket { and ends with a right curly bracket }.
Multiple key/value pairs are separated by a comma ,.
 Array: This is defined as an ordered list of values. An array begins with a
left bracket [ and ends with a right bracket ]. Values are separated by a comma ,.
In JSON, keys are always strings, while the value can be
a string, number, true or false, null or even an object or an array. Strings must be
enclosed in double quotes " and can contain escape characters such
as \n, \t and \. A JSON object may look like this:

Example
Run this code »
{
"book":{
"name":"Harry Potter and the Goblet of Fire",
"author":"J. K. Rowling",
"year":2000,
"genre":"Fantasy Fiction",
"bestseller":true
}
}

Whereas an example of JSON array would look something like this:

Example
Run this code »
{
"fruits":[
"Apple",
"Banana",
"Strawberry",
"Mango"
]
}

Tip: A data-interchange format is a text format which is used to interchange or


exchange data between different platforms and operating systems. JSON is the
most popular and lightweight data-interchange format for web applications.

Parsing JSON with PHP


JSON data structures are very similar to PHP arrays. PHP has built-in functions to
encode and decode JSON data. These functions
are json_encode() and json_decode(), respectively. Both functions only works with
UTF-8 encoded string data.

Encoding JSON Data in PHP


In PHP the json_encode() function is used to encode a value to JSON format. The
value being encoded can be any PHP data type except a resource, like a database
or file handle. The below example demonstrates how to encode a PHP associative
array into a JSON object:

Example
Run this code »
<?php
// An associative array
$marks=array("Peter"=>65,"Harry"=>80,"John"=>78,"Clark"=>90);

echojson_encode($marks);
?>

The output of the above example will look like this:


{"Peter":65,"Harry":80,"John":78,"Clark":90}

Similarly, you can encode the PHP indexed array into a JSON array, like this:

Example
Run this code »
<?php
// An indexed array
$colors=array("Red","Green","Blue","Orange","Yellow");

echojson_encode($colors);
?>

The output of the above example will look like this:


["Red","Green","Blue","Orange","Yellow"]

You can also force json_encode() function to return an PHP indexed array as JSON


object by using the JSON_FORCE_OBJECT option, as shown in the example below:

Example
Run this code »
<?php
// An indexed array
$colors=array("Red","Green","Blue","Orange");

echojson_encode($colors,JSON_FORCE_OBJECT);
?>

The output of the above example will look like this:


{"0":"Red","1":"Green","2":"Blue","3":"Orange"}

As you can see in the above examples a non-associative array can be encoded as
array or object. However, an associative array always encoded as object.

Decoding JSON Data in PHP


Decoding JSON data is as simple as encoding it. You can use the
PHP json_decode() function to convert the JSON encoded string into appropriate
PHP data type. The following example demonstrates how to decode or convert a
JSON object to PHP object.

Example
Run this code »
<?php
// Store JSON data in a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';

var_dump(json_decode($json));
?>

The output of the above example will look something like this:
object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(80)
["John"]=> int(78) ["Clark"]=> int(90) }

By default the json_decode() function returns an object. However, you can


optionally specify a second parameter $assoc which accepts a boolean value that
when set as true JSON objects are decoded into associative arrays. It is false by
default. Here's an example:
Example
Run this code »
<?php
// Store JSON data in a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';

var_dump(json_decode($json,true));
?>

The output of the above example will look something like this:
array(4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=>
int(78) ["Clark"]=> int(90) }

Now let's check out an example that will show you how to decode the JSON data
and access individual elements of the JSON object or array in PHP.

Example
Run this code »
<?php
// Assign JSON encoded string to a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';

// Decode JSON data to PHP associative array


$arr=json_decode($json,true);
// Access values from the associative array
echo$arr["Peter"];// Output: 65
echo$arr["Harry"];// Output: 80
echo$arr["John"];// Output: 78
echo$arr["Clark"];// Output: 90

// Decode JSON data to PHP object


$obj=json_decode($json);
// Access values from the returned object
echo$obj->Peter;// Output: 65
echo$obj->Harry;// Output: 80
echo$obj->John;// Output: 78
echo$obj->Clark;// Output: 90
?>

You can also loop through the decoded data using foreach() loop, like this:

Example
Run this code »
<?php
// Assign JSON encoded string to a PHP variable
$json='{"Peter":65,"Harry":80,"John":78,"Clark":90}';

// Decode JSON data to PHP associative array


$arr=json_decode($json,true);

// Loop through the associative array


foreach($arras$key=>$value){
echo$key."=>".$value."<br>";
}
echo"<hr>";
// Decode JSON data to PHP object
$obj=json_decode($json);

// Loop through the object


foreach($objas$key=>$value){
echo$key."=>".$value."<br>";
}
?>

Extracting Values from Nested JSON Data in PHP


JSON objects and arrays can also be nested. A JSON object can arbitrarily
contains other JSON objects, arrays, nested arrays, arrays of JSON objects, and so
on. The following example will show you how to decode a nested JSON object
and print all its values in PHP.

Example
Run this code »
<?php
// Define recursive function to extract nested values
functionprintValues($arr){
global$count;
global$values;

// Check input is an array


if(!is_array($arr)){
die("ERROR: Input is not an array");
}
/*
Loop through array, if value is itself an array recursively
call the
function else add the value found to the output items array,

and increment counter by 1 for each value found

*/

foreach($arras$key=>$value){

if(is_array($value)){

printValues($value);

}else{

$values[]=$value;

$count++;

// Return total count and values found in array

returnarray('total'=>$count,'values'=>$values);

}// Assign JSON encoded string to a PHP variable

$json='{

"book": {

"name": "Harry Potter and the Goblet of Fire",

"author": "J. K. Rowling",

"year": 2000,

"characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],


"genre": "Fantasy Fiction",

"price": {

"paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11"

}
}';

// Decode JSON data into PHP associative array format

$arr=json_decode($json,true);

// Call the function and print all the values

$result=printValues($arr);

echo"<h3>".$result["total"]." value(s) found: </h3>";

echoimplode("<br>",$result["values"]);

echo"<hr>";

// Print a single value

echo$arr["book"]["author"]."<br>";// Output: J. K. Rowling

echo$arr["book"]["characters"][0]."<br>";// Output: Harry Potter

echo$arr["book"]["price"]["hardcover"];// Output: $20.32

?>
Chapter 34

PHP Regular Expressions
In this tutorial you will learn how regular expressions work, as well as how to use
them to perform pattern matching in an efficient way in PHP.

What is Regular Expression


Regular Expressions, commonly known as "regex" or "RegExp", are a specially
formatted text strings used to find patterns in text. Regular expressions are one
of the most powerful tools available today for effective and efficient text
processing and manipulations. For example, it can be used to verify whether the
format of data i.e. name, email, phone number, etc. entered by the user was
correct or not, find or replace matching string within text content, and so on.

PHP (version 5.3 and above) supports Perl style regular expressions via
its preg_ family of functions. Why Perl style regular expressions? Because Perl
(Practical Extraction and Report Language) was the first mainstream programming
language that provided integrated support for regular expressions and it is well
known for its strong support of regular expressions and its extraordinary text
processing and manipulation capabilities.

Let's begin with a brief overview of the commonly used PHP's built-in pattern-
matching functions before delving deep into the world of regular expressions.

Function What it Does

preg_match() Perform a regular expression match.

preg_match_all() Perform a global regular expression match.

preg_replace() Perform a regular expression search and replace.

preg_grep() Returns the elements of the input array that


matched the pattern.

preg_split() Splits up a string into substrings using a regular


expression.

preg_quote() Quote regular expression characters found within


a string.

Note: The PHP preg_match() function stops searching after it finds the first


match, whereas the preg_match_all() function continues searching until the end
of the string and find all possible matches instead of stopping at the first match.

Regular Expression Syntax


Regular expression syntax includes the use of special characters (do not confuse
with the HTML special characters). The characters that are given special meaning
within a regular expression, are: . * ? + [ ] ( ) { } ^ $ | \. You will need to
backslash these characters whenever you want to use them literally. For example,
if you want to match ".", you'd have to write \.. All other characters automatically
assume their literal meanings.
The following sections describe the various options available for formulating
patterns:

Character Classes
Square brackets surrounding a pattern of characters are called a character class
e.g. [abc]. A character class always matches a single character out of a list of
specified characters that means the expression [abc] matches only a, b or c
character.

Negated character classes can also be defined that match any character except
those contained within the brackets. A negated character class is defined by
placing a caret (^) symbol immediately after the opening bracket, like this [^abc].

You can also define a range of characters by using the hyphen ( -) character inside
a character class, like [0-9]. Let's look at some examples of character classes:

RegExp What it Does

[abc] Matches any one of the characters a, b, or c.

[^abc] Matches any one character other than a, b, or c.

[a-z] Matches any one character from lowercase a to lowercase z.

[A-Z] Matches any one character from uppercase a to uppercase z.

[a-Z] Matches any one character from lowercase a to uppercase Z.

[0-9] Matches a single digit between 0 and 9.

[a-z0- Matches a single character between a and z or between 0


9] and 9.

The following example will show you how to find whether a pattern exists in a
string or not using the regular expression and PHP preg_match() function:

Example
Run this code »
<?php
$pattern="/ca[kf]e/";
$text="He was eating cake in the cafe.";
if(preg_match($pattern,$text)){
echo"Match found!";
}else{
echo"Match not found.";
}
?>
Similarly, you can use the preg_match_all() function to find all matches within a
string:

Example
Run this code »

<?php
$pattern="/ca[kf]e/";
$text="He was eating cake in the cafe.";
$matches=preg_match_all($pattern,$text,$array);
echo$matches." matches were found.";
?>
Tip: Regular expressions aren't exclusive to PHP. Languages such as Java, Perl,
Python, etc. use the same notation for finding patterns in text.

Predefined Character Classes


Some character classes such as digits, letters, and whitespaces are used so
frequently that there are shortcut names for them. The following table lists those
predefined character classes:

Shortcu What it Does


t

. Matches any single character except newline \n.

\d matches any digit character. Same as [0-9]

\D Matches any non-digit character. Same as [^0-9]


Shortcu What it Does
t

\s Matches any whitespace character (space, tab, newline or


carriage return character). Same as [ \t\n\r]

\S Matches any non-whitespace character. Same as [^ \t\n\r]

\w Matches any word character (definned as a to z, A to Z,0 to 9,


and the underscore). Same as [a-zA-Z_0-9]

\W Matches any non-word character. Same as [^a-zA-Z_0-9]

The following example will show you how to find and replace space with a
hyphen character in a string using regular expression and
PHP preg_replace() function:

Example
Run this code »

<?php
$pattern="/\s/";
$replacement="-";
$text="Earth revolves around\nthe\tSun";
// Replace spaces, newlines and tabs
echopreg_replace($pattern,$replacement,$text);
echo"<br>";
// Replace only spaces
echostr_replace(" ","-",$text);
?>

Repetition Quantifiers
In the previous section we've learnt how to match a single character in a variety
of fashions. But what if you want to match on more than one character? For
example, let's say you want to find out words containing one or more instances
of the letter p, or words containing at least two p's, and so on. This is where
quantifiers come into play. With quantifiers you can specify how many times a
character in a regular expression should match.

The following table lists the various ways to quantify a particular pattern:

RegExp What it Does

p+ Matches one or more occurrences of the letter p.

p* Matches zero or more occurrences of the letter p.

p? Matches zero or one occurrences of the letter p.

p{2} Matches exactly two occurrences of the letter p.

p{2,3} Matches at least two occurrences of the letter p, but not


more than three occurrences of the letter p.

p{2,} Matches two or more occurrences of the letter p.

p{,3} Matches at most three occurrences of the letter p

The regular expression in the following example will splits the string at comma,
sequence of commas, whitespace, or combination thereof using the
PHP preg_split() function:

Example
Run this code »

<?php
$pattern="/[\s,]+/";
$text="My favourite colors are red, green and blue";
$parts=preg_split($pattern,$text);
// Loop through parts array and display substrings
foreach($partsas$part){
echo$part."<br>";
}
?>

Position Anchors
There are certain situations where you want to match at the beginning or end of
a line, word, or string. To do this you can use anchors. Two common anchors are
caret (^) which represent the start of the string, and the dollar ( $) sign which
represent the end of the string.

RegExp What it Does

^p Matches the letter p at the beginning of a line.

p$ Matches the letter p at the end of a line.

The regular expression in the following example will display only those names
from the names array which start with the letter "J" using the
PHP preg_grep() function:

Example
Run this code »

<?php
$pattern="/^J/";
$names=array("Jhon Carter","Clark Kent","John Rambo");
$matches=preg_grep($pattern,$names);

// Loop through matches array and display matched names


foreach($matchesas$match){
echo$match."<br>";
}
?>
Pattern Modifiers
A pattern modifier allows you to control the way a pattern match is handled.
Pattern modifiers are placed directly after the regular expression, for example, if
you want to search for a pattern in a case-insensitive manner, you can use
the i modifier, like this: /pattern/i. The following table lists some of the most
commonly used pattern modifiers.

Modifier What it Does

i Makes the match case-insensitive manner.

m Changes the behavior of ^ and $ to match against a newline


boundary (i.e. start or end of each line within a multiline
string), instead of a string boundary.

g Perform a global match i.e. finds all occurrences.

o Evaluates the expression only once.

s Changes the behavior of . (dot) to match all characters,


including newlines.

x Allows you to use whitespace and comments within a regular


expression for clarity.

The following example will show you how to perform a global case-insensitive
search using the i modifier and the PHP preg_match_all() function.

Example
Run this code »

<?php
$pattern="/color/i";
$text="Color red is more visible than color blue in daylight.";
$matches=preg_match_all($pattern,$text,$array);
echo$matches." matches were found.";
?>
Similarly, the following example shows how to match at the beginning of every
line in a multi-line string using ^ anchor and m modifier with
PHP preg_match_all() function.

Example
Run this code »

<?php
$pattern="/^color/im";
$text="Color red is more visible than \ncolor blue in daylight.";
$matches=preg_match_all($pattern,$text,$array);
echo$matches." matches were found.";
?>

Word Boundaries
A word boundary character ( \b) helps you search for the words that begins
and/or ends with a pattern. For example, the regexp /\bcar/ matches the words
beginning with the pattern car, and would match cart, carrot, or cartoon, but
would not match oscar.

Similarly, the regexp /car\b/ matches the words ending with the pattern car, and
would match scar, oscar, or supercar, but would not match cart. Likewise,
the /\bcar\b/ matches the words beginning and ending with the pattern car, and
would match only the word car.

The following example will highlight the words beginning with car in bold:

Example
Run this code »

<?php
$pattern='/\bcar\w*/';
$replacement='<b>$0</b>';
$text='Words begining with car: cart, carrot, cartoon. Words
ending with car: scar, oscar, supercar.';
echopreg_replace($pattern,$replacement,$text);
?>

We hope you have understood the basics of regular expression. To learn how to
validate form data using regular expression, please check out the tutorial on PHP
Form Validation.

Chapter 35

PHP Exception Handling
In this tutorial you will learn how to throw and catch exceptions in PHP.

What is an Exception
An exception is a signal that indicates some sort of exceptional event or error has
occurred. Exceptions can be caused due to various reasons, for example,
database connection or query fails, file that you're trying to access doesn't exist,
and so on.

PHP provides a powerful exception handling mechanism that allows you to


handle exceptions in a graceful way. As opposed to PHP's traditional error-
handling system, exception handling is the object-oriented method for handling
errors, which provides more controlled and flexible form of error reporting.
Exception model was first introduced in PHP 5.

Using Throw and Try...Catch Statements


In exception-based approach, program code is written in a try block, an
exception can be thrown using the throw statement when an exceptional event
occurs during the execution of code in a try block. It is then caught and resolved
by one or more catch blocks.

The following example demonstrates how exception handling works:


Example
Download

<?php
functiondivision($dividend,$divisor){
// Throw exception if divisor is zero
if($divisor==0){
thrownewException('Division by zero.');
}else{
$quotient=$dividend/$divisor;
echo"<p>$dividend / $divisor = $quotient</p>";
}
}

try{
division(10,2);
division(30,-4);
division(15,0);

// If exception is thrown following line won't execute


echo'<p>All divisions performed successfully.</p>';
}catch(Exception $e){
// Handle the exception
echo"<p>Caught exception: ".$e->getMessage()."</p>";
}

// Continue execution
echo"<p>Hello World!</p>";
?>

You might be wondering what this code was all about. Well, let's go through
each part of this code one by one for a better understanding.

Explanation of Code
The PHP's exception handling system has basically four parts: try, throw, catch, and
the Exception class. The following list describes how each part exactly works.

 The division() function in the example above checks if a divisor is equal


to zero. If it is, an exception is thrown via PHP's throw statement. Otherwise this
function perform the division using given numbers and display the result.
 Later, the division() function is called within a try block with different
arguments. If an exception is generated while executing the code within
the try block, PHP stops execution at that point and attempt to find the
corresponding catch block. If it is found, the code within that catch block is
executed, if not, a fatal error is generated.
 The catch block typically catch the exception thrown within the try block
and creates an object ($e) containing the exception information. The error
message from this object can be retrieved using the
Exception's getMessage() method.

The PHP's Exception class also


provides getCode(), getFile(), getLine() and getTraceAsString() methods that can be
used to generate detailed debugging information.

Example
Download

<?php
// Turn off default error reporting
error_reporting(0);

try{
$file="somefile.txt";

// Attempt to open the file


$handle=fopen($file,"r");
if(!$handle){
thrownewException("Cannot open the file!",5);
}

// Attempt to read the file contents


$content=fread($handle,filesize($file));
if(!$content){
thrownewException("Could not read file!",10);
}

// Closing the file handle


fclose($handle);

// Display file contents


echo$content;
}catch(Exception $e){
echo"<h3>Caught Exception!</h3>";
echo"<p>Error message: ".$e->getMessage()."</p>";
echo"<p>File: ".$e->getFile()."</p>";
echo"<p>Line: ".$e->getLine()."</p>";
echo"<p>Error code: ".$e->getCode()."</p>";
echo"<p>Trace: ".$e->getTraceAsString()."</p>";
}
?>

The Exception's constructor optionally takes an exception message and an


exception code. While the exception message is typically used to display generic
information on what went wrong, the exception code can be used to categorize
the errors. The exception code provided can be retrieved later via
Exception's getCode() method.

Tip: Exception should only be used to denote exceptional conditions; they should


not be used to control normal application flow e.g., jump to another place in the
script at a particular point. Doing that would adversely affect your application's
performance.

Defining Custom Exceptions


You can even define your own custom exception handlers to treat different types
of exceptions in a different way. It allows you to use a separate catch block for
each exception type.

You can define a custom exception by extending the Exception class, because
Exception is the base class for all exceptions. The custom exception class inherits
all the properties and methods from PHP's Exception class. You can also add your
custom methods to the custom exception class. Let's check out the following
example:

Example
Download

<?php
// Extending the Exception class
classEmptyEmailExceptionextendsException{}
classInvalidEmailExceptionextendsException{}

$email="[email protected]";
try{
// Throw exception if email is empty
if($email==""){
thrownewEmptyEmailException("<p>Please enter your E-mail address!
</p>");
}

// Throw exception if email is not valid


if(filter_var($email,FILTER_VALIDATE_EMAIL)===FALSE){
thrownewInvalidEmailException("<p><b>$email</b> is not a valid E-
mail address!</p>");
}

// Display success message if email is valid


echo"<p>SUCCESS: Email validation successful.</p>";
}catch(EmptyEmailException $e){
echo$e->getMessage();
}catch(InvalidEmailException $e){
echo$e->getMessage();
}
?>

In the above example we've derived two new exception


classes: EmptyEmailException, and InvalidEmailException from the Exception
base class. Multiple catch blocks are used to display different error messages,
depending on the type of exception generated.

Since these custom exception classes inherits the properties and methods from
the Exception class, so we can use the Exception's class methods
like getMessage(), getLine(), getFile(), etc. to retrieve error information from the
exception object.

Setting a Global Exception Handler


As we've discussed earlier in this chapter if an exception is not caught, PHP
generates a Fatal Error with an "Uncaught Exception ..." message. This error
message may contain sensitive information like file name and line number where
the problem occurs. If you don't want to expose such information to the user, you
can create a custom function and register it with
the set_exception_handler() function to handle all uncaught exceptions.

Example
Download

<?php
functionhandleUncaughtException($e){
// Display generic error message to the user
echo"Opps! Something went wrong. Please try again, or contact us
if the problem persists.";

// Construct the error string


$error="Uncaught Exception: ".$message=date("Y-m-d H:i:s - ");
$error.=$e->getMessage()." in file ".$e->getFile()." on line ".
$e->getLine()."\n";

// Log details of error in a file


error_log($error,3,"var/log/exceptionLog.log");
}

// Register custom exception handler


set_exception_handler("handleUncaughtException");

// Throw an exception
thrownewException("Testing Exception!");
?>

Note: An uncaught exception will always result in script termination. So if you


want the script to continue executing beyond the point where the exception
occurred, you must have have at least one corresponding catch block for
each try block.
Chapter 36

PHP MySQL Introduction
MySQL is the most popular database system used with the PHP language.

What is MySQL
MySQL is one of the most popular relational database system being used on the
Web today. It is freely available and easy to install, however if you have installed
Wampserver it already there on your machine. MySQL database server offers
several advantages:

 MySQL is easy to use, yet extremely powerful, fast, secure, and scalable.
 MySQL runs on a wide range of operating systems, including UNIX or
Linux, Microsoft Windows, Apple Mac OS X, and others.
 MySQL supports standard SQL (Structured Query Language).
 MySQL is ideal database solution for both small and large applications.
 MySQL is developed, and distributed by Oracle Corporation.
 MySQL includes data security layers that protect sensitive data from
intruders.

MySQL database stores data into tables like other relational database. A table is a
collection of related data, and it is divided into rows and columns.

Each row in a table represents a data record that are inherently connected to
each other such as information related to a particular person, whereas each
column represents a specific field such as id, first_name, last_name, email, etc. The
structure of a simple MySQL table that contains person's general information
may look something like this:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

Tip: Websites like Facebook, Twitter, Wikipedia uses MySQL for their storage
need. So you can easily understand what MySQL is capable of.
Talking to MySQL Databases with SQL
SQL, the Structured Query Language, is a simple, standardized language for
communicating with relational databases like MySQL. With SQL you can perform
any database-related task, such as creating databases and tables, saving data in
database tables, query a database for specific records, deleting and updating
data in databases.

Look at the following standard SQL query that returns the email address of a
person whose first name is equal to 'Peter' in the persons table:
SELECT email FROM persons WHERE first_name="Peter"

If you execute the SQL query above it will return the following record:

[email protected]

To learn more about SQL, please checkout the SQL tutorial section.

Chapter 37

PHP Connect to MySQL Server
In this tutorial you will learn how to connect to the MySQL server using PHP.

Ways of Connecting to MySQL through PHP


In order to store or access the data inside a MySQL database, you first need to
connect to the MySQL database server. PHP offers two different ways to connect
to MySQL server: MySQLi (Improved MySQL) and PDO (PHP Data Objects)
extensions.

While the PDO extension is more portable and supports more than twelve
different databases, MySQLi extension as the name suggests supports MySQL
database only. MySQLi extension however provides an easier way to connect to,
and execute queries on, a MySQL database server. Both PDO and MySQLi offer an
object-oriented API, but MySQLi also offers a procedural API which is relatively
easy for beginners to understand.

Tip: The PHP's MySQLi extension provides both speed and feature benefits over
the PDO extension, so it could be a better choice for MySQL-specific projects.

Connecting to MySQL Database Server


In PHP you can easily do this using the mysqli_connect() function. All
communication between PHP and the MySQL database server takes place
through this connection. Here're the basic syntaxes for connecting to MySQL
using MySQLi and PDO extensions:

Syntax: MySQLi, Procedural way


$link = mysqli_connect("hostname", "username", "password", "database");

Syntax: MySQLi, Object Oriented way


$mysqli = new mysqli("hostname", "username", "password", "database");

Syntax: PHP Data Objects (PDO) way


$pdo = new PDO("mysql:host=hostname;dbname=database", "username",
"password");

The hostname parameter in the above syntax specify the host name


(e.g. localhost), or IP address of the MySQL server, whereas
the username and password parameters specifies the credentials to access MySQL
server, and the database parameter, if provided will specify the default MySQL
database to be used when performing queries.

The following example shows how to connect to MySQL database server using
MySQLi (both procedural and object oriented way) and PDO extension.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Print host information


echo"Connect Successfully. Host info:
".mysqli_get_host_info($link);

?>

Note: The default username for MySQL database server is root and there is no


password. However to prevent your databases from intrusion and unauthorized
access you should set password for MySQL accounts.

Tip: Setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION tells


PDO to throw exceptions whenever a database error occurs.

Closing the MySQL Database Server Connection


The connection to the MySQL database server will be closed automatically as
soon as the execution of the script ends. However, if you want to close it earlier
you can do this by simply calling the PHP mysqli_close() function.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","");
// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Print host information

echo"Connect Successfully. Host info:


".mysqli_get_host_info($link);

// Close connection

mysqli_close($link);

?>
Chapter 38
PHP MySQL Create Database
In this tutorial you will learn how to create a database in MySQL using PHP.

Creating MySQL Database Using PHP


Now that you've understood how to open a connection to the MySQL database
server. In this tutorial you will learn how to execute SQL query to create a
database.
Before saving or accessing the data, we need to create a database first. The CREATE
DATABASE statement is used to create a new database in MySQL.

Let's make a SQL query using the CREATE DATABASE statement, after that we will
execute this SQL query through passing it to the PHP mysqli_query() function to
finally create our database. The following example creates a database
named demo.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

}
// Attempt create database query execution

$sql="CREATE DATABASE demo";

if(mysqli_query($link,$sql)){

echo"Database created successfully";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
Tip: Setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION tells PDO to
throw exceptions whenever a database error occurs.
Chapter 39

PHP MySQL Create Tables
In this tutorial you will learn how to create tables in MySQL database using PHP.

Creating Tables inside MySQL Database Using PHP


In the previous chapter we've learned how to create a database on MySQL server.
Now it's time to create some tables inside the database that will actually hold the
data. A table organizes the information into rows and columns.

The SQL CREATE TABLE statement is used to create a table in database.

Let's make a SQL query using the CREATE TABLE statement, after that we will
execute this SQL query through passing it to the PHP mysqli_query() function to
finally create our table.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

}
// Attempt create table query execution

$sql="CREATE TABLE persons(

id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,

first_name VARCHAR(30) NOT NULL,

last_name VARCHAR(30) NOT NULL,

email VARCHAR(70) NOT NULL UNIQUE

)";

if(mysqli_query($link,$sql)){

echo"Table created successfully.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);
?>
The PHP code in the above example creates a table named persons with four
columns id, first_name, last_name and email inside the demo database.

Notice that each field name is followed by a data type declaration; this
declaration specifies what type of data the column can hold, whether integer,
string, date, etc.

There are a few additional constraints (also called modifiers) that are specified
after the column name in the preceding SQL statement, like NOT NULL, PRIMARY
KEY, AUTO_INCREMENT, etc. Constraints define rules regarding the values allowed in
columns.

Please check out the tutorial on SQL CREATE TABLE statement for the detailed


information about syntax, as well as the data types and constraints available in
MySQL database system.

Note: Any number of line breaks may occur within a SQL statement, provided
that any line break does not break off keywords, values, expression, etc.

Tip: Setting the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION tells PDO to


throw exceptions whenever a database error occurs.

Chapter 40

PHP MySQL INSERT Query
In this tutorial you will learn how to insert records in a MySQL table using PHP.
Inserting Data into a MySQL Database Table
Now that you've understood how to create database and tables in MySQL. In this
tutorial you will learn how to execute SQL query to insert records into a table.

The INSERT INTO statement is used to insert new rows in a database table.

Let's make a SQL query using the INSERT INTO statement with appropriate values,
after that we will execute this insert query through passing it to the
PHP mysqli_query() function to insert data in table. Here's an example, which insert
a new row to the persons table by specifying values for
the first_name, last_name and email fields.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());


}

// Attempt insert query execution

$sql="INSERT INTO persons (first_name, last_name, email) VALUES


('Peter', 'Parker', '[email protected]')";

if(mysqli_query($link,$sql)){

echo"Records inserted successfully.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
If you remember from the preceding chapter, the id field was marked with
the AUTO_INCREMENT flag. This modifier tells the MySQL to automatically assign a
value to this field if it is left unspecified, by incrementing the previous value by 1.
Inserting Multiple Rows into a Table
You can also insert multiple rows into a table with a single insert query at once.
To do this, include multiple lists of column values within the INSERT
INTO statement, where column values for each row must be enclosed within
parentheses and separated by a comma.

Let's insert few more rows into the persons table, like this:

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

}
// Attempt insert query execution

$sql="INSERT INTO persons (first_name, last_name, email) VALUES

('John', 'Rambo', '[email protected]'),

('Clark', 'Kent', '[email protected]'),

('John', 'Carter', '[email protected]'),

('Harry', 'Potter', '[email protected]')";

if(mysqli_query($link,$sql)){

echo"Records added successfully.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
Now, go to phpMyAdmin (http://localhost/phpmyadmin/) and check out
the persons table data inside demo database. You will find the value for
the id column is assigned automatically by incrementing the value of
previous id by 1.

Note: Any number of line breaks may occur within a SQL statement, provided
that any line break does not break off keywords, values, expression, etc.

Insert Data into a Database from an HTML Form


In the previous section, we have learned how to insert data into database from a
PHP script. Now, we'll see how we can insert data into database obtained from an
HTML form. Let's create an HTML form that can be used to insert new records
to persons table.

Step 1: Creating the HTML Form


Here's a simple HTML form that has three text <input> fields and a submit button.

Example
Download

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php"method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text"name="first_name"id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text"name="last_name"id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text"name="email"id="emailAddress">
</p>
<input type="submit"value="Submit">
</form>
</body>
</html>

Step 2: Retrieving and Inserting the Form Data


When a user clicks the submit button of the form add record HTML form, in the
example above, the form data is sent to 'insert.php' file. The 'insert.php' file
connects to the MySQL database server, retrieves forms fields using the
PHP $_REQUEST variables and finally execute the insert query to add the records.
Here is the complete code of our 'insert.php' file:

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());


}

// Escape user inputs for security

$first_name=mysqli_real_escape_string($link,
$_REQUEST['first_name']);

$last_name=mysqli_real_escape_string($link,
$_REQUEST['last_name']);

$email=mysqli_real_escape_string($link,$_REQUEST['email']);

// Attempt insert query execution

$sql="INSERT INTO persons (first_name, last_name, email) VALUES


('$first_name', '$last_name', '$email')";

if(mysqli_query($link,$sql)){

echo"Records added successfully.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

}
// Close connection

mysqli_close($link);

?>
In the next chapter we will extend this insert query example and take it one step
further by implementing the prepared statement for better security and
performance.

Note: The mysqli_real_escape_string() function escapes special characters in a


string and create a legal SQL string to provide security against SQL injection.

This is very basic example of inserting the form data in a MySQL database table.
You can extend this example and make it more interactive by adding validations
to the user inputs before inserting it to the database tables. Please check out the
tutorial on PHP form validation to learn more about sanitizing and validating user
inputs using PHP.

Chapter 41

PHP MySQL Prepared Statements
In this tutorial you will learn how to use prepared statements in MySQL using
PHP.

What is Prepared Statement


A prepared statement (also known as parameterized statement) is simply a SQL
query template containing placeholder instead of the actual parameter values.
These placeholders will be replaced by the actual values at the time of execution
of the statement.

MySQLi supports the use of anonymous positional placeholder (?), as shown


below:
INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?);

While, PDO supports both anonymous positional placeholder (?), as well as the
named placeholders. A named placeholder begins with a colon ( :) followed by an
identifier, like this:
INSERT INTO persons (first_name, last_name, email)
VALUES (:first_name, :last_name, :email);

The prepared statement execution consists of two stages: prepare and execute.

 Prepare — At the prepare stage a SQL statement template is created and


sent to the database server. The server parses the statement template, performs a
syntax check and query optimization, and stores it for later use.
 Execute — During execute the parameter values are sent to the server. The
server creates a statement from the statement template and these values to
execute it.

Prepared statements is very useful, particularly in situations when you execute a


particular statement multiple times with different values, for example, a series
of INSERT statements. The following section describes some of the major benefits
of using it.

Advantages of Using Prepared Statements


A prepared statement can execute the same statement repeatedly with high
efficiency, because the statement is parsed only once again, while it can be
executed multiple times. It also minimize bandwidth usage, since upon every
execution only the placeholder values need to be transmitted to the database
server instead of the complete SQL statement.

Prepared statements also provide strong protection against SQL injection,


because parameter values are not embedded directly inside the SQL query string.
The parameter values are sent to the database server separately from the query
using a different protocol and thus cannot interfere with it. The server uses these
values directly at the point of execution, after the statement template is parsed.
That's why the prepared statements are less error-prone, and thus considered as
one of the most critical element in database security.

The following example will show you how prepared statements actually work:

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());


}

// Prepare an insert statement

$sql="INSERT INTO persons (first_name, last_name, email) VALUES


(?, ?, ?)";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"sss",$first_name,$last_name,
$email);

/* Set the parameters values and execute

the statement again to insert another row */

$first_name="Hermione";

$last_name="Granger";

$email="[email protected]";

mysqli_stmt_execute($stmt);
/* Set the parameters values and execute

the statement to insert a row */

$first_name="Ron";

$last_name="Weasley";

$email="[email protected]";

mysqli_stmt_execute($stmt);

echo"Records inserted successfully.";

}else{

echo"ERROR: Could not prepare query: $sql. ".mysqli_error($link);

// Close statement

mysqli_stmt_close($stmt);
// Close connection

mysqli_close($link);

?>
As you can see in the above example we've prepared the INSERT statement just
once but executed it multiple times by passing the different set of parameters.

Explanation of Code (Procedural style)


Inside the SQL INSERT statement (line no-12) of the example above, the question
marks is used as the placeholders for the first_name, last_name, email fields
values.

The mysqli_stmt_bind_param() function (line no-16) bind variables to the


placeholders (?) in the SQL statement template. The placeholders (?) will be
replaced by the actual values held in the variables at the time of execution.
The type definition string provided as second argument i.e. the "sss" string
specifies that the data type of each bind variable is string.

The type definition string specify the data types of the corresponding bind
variables and contains one or more of the following four characters:

 b — binary (such as image, PDF file, etc.)


 d — double (floating point number)
 i — integer (whole number)
 s — string (text)

The number of bind variables and the number of characters in type definition
string must match the number of placeholders in the SQL statement template.

Using Inputs Received through a Web Form


If you remember from the previous chapter, we've created an HTML form
to insert data into database. Here, we're going to extend that example by
implementing the prepared statement. You can use the same HTML form to test
the following insert script example, but just make sure that you're using the
correct file name in the action attribute of the form.

Here's the updated PHP code for inserting the data. If you see the example
carefully you'll find we didn't use the mysqli_real_escape_string() to escape the
user inputs, like we've done in the previous chapter example. Since in prepared
statements, user inputs are never substituted into the query string directly, so
they do not need to be escaped correctly.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());


}

// Prepare an insert statement

$sql="INSERT INTO persons (first_name, last_name, email) VALUES


(?, ?, ?)";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"sss",$first_name,$last_name,
$email);

// Set parameters

$first_name=$_REQUEST['first_name'];

$last_name=$_REQUEST['last_name'];

$email=$_REQUEST['email'];

// Attempt to execute the prepared statement


if(mysqli_stmt_execute($stmt)){

echo"Records inserted successfully.";

}else{

echo"ERROR: Could not execute query: $sql. ".mysqli_error($link);

}else{

echo"ERROR: Could not prepare query: $sql. ".mysqli_error($link);

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

?>
Note: Though escaping user inputs is not required in prepared statements, you
should always validate the type and size of the data received from external
sources and enforces appropriate limits to protect against system resources
exploitation.

Chapter 42

PHP MySQL Last Inserted ID


In this tutorial you will learn how to retrieve the unique ID of the last inserted row
from a MySQL database table using PHP.

How to Get the ID of Last Inserted Row


In the PHP MySQL insert chapter you've learnt MySQL automatically generate an
unique ID for the AUTO_INCREMENT column each time you insert a new record or row
into the table. However, there are certain situations when you need that
automatically generated ID to insert it into a second table. In these situations you
can use the PHP mysqli_insert_id() function to retrieve the most recently
generated ID, as shown in the upcoming example.

For this example we'll use the same persons table that we've created in the PHP
MySQL create tables chapter, which has four
columns id, first_name, last_name and email, where id is the primary key column
and marked with AUTO_INCREMENT flag.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());


}

// Attempt insert query execution

$sql="INSERT INTO persons (first_name, last_name, email) VALUES


('Ron', 'Weasley', '[email protected]')";

if(mysqli_query($link,$sql)){

// Obtain last inserted id

$last_id=mysqli_insert_id($link);

echo"Records inserted successfully. Last inserted ID is: ".


$last_id;

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
Chapter 43

PHP MySQL SELECT Query
In this tutorial you'll learn how to select records from a MySQL table using PHP.
Selecting Data From Database Tables
So far you have learnt how to create database and table as well as inserting data.
Now it's time to retrieve data what have inserted in the preceding tutorial. The
SQL SELECT statement is used to select the records from database tables. Its basic
syntax is as follows:
SELECT column1_name, column2_name, columnN_name FROM table_name;

Let's make a SQL query using the SELECT statement, after that we will execute this
SQL query through passing it to the PHP mysqli_query() function to retrieve the
table data.

Consider our persons database table has the following records:


+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example selects all the data stored in
the persons table (using the asterisk character (*) in place of column name selects
all the data in the table).

Example
Procedural   Object Oriented   PDO

Download

<?php
/* Attempt MySQL server connection. Assuming you are running
MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Attempt select query execution

$sql="SELECT * FROM persons";

if($result=mysqli_query($link,$sql)){

if(mysqli_num_rows($result)>0){

echo"<table>";

echo"<tr>";

echo"<th>id</th>";
echo"<th>first_name</th>";

echo"<th>last_name</th>";

echo"<th>email</th>";

echo"</tr>";

while($row=mysqli_fetch_array($result)){

echo"<tr>";

echo"<td>".$row['id']."</td>";

echo"<td>".$row['first_name']."</td>";

echo"<td>".$row['last_name']."</td>";

echo"<td>".$row['email']."</td>";

echo"</tr>";

echo"</table>";

// Free result set

mysqli_free_result($result);

}else{
echo"No records matching your query were found.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>

Explanation of Code (Procedural style)


In the example above, the data returned by the mysqli_query() function is stored in
the $result variable. Each time mysqli_fetch_array() is invoked, it returns the next
row from the result set as an array. The while loop is used to loops through all
the rows in the result set. Finally the value of individual field can be accessed
from the row either by passing the field index or field name to the $row variable
like $row['id'] or $row[0], $row['first_name'] or $row[1], $row['last_name'] or $row[2],
and $row['email'] or $row[3].

If you want to use the for loop you can obtain the loop counter value or the
number of rows returned by the query by passing the $result variable to
the mysqli_num_rows() function. This loop counter value determines how many
times the loop should run.
Chapter 44

PHP MySQL WHERE Clause
In this tutorial you will learn how to select the records from a MySQL database
table based on specific conditions using PHP.

Filtering the Records


The WHERE clause is used to extract only those records that fulfill a specified
condition.

The basic syntax of the WHERE clause can be given with:


SELECT column_name(s) FROM table_name WHERE column_name operator value

Let's make a SQL query using the WHERE clause in SELECT statement, after that we'll
execute this query through passing it to the PHP mysqli_query() function to get
the filtered data.

Consider we've a persons table inside the demo database that has following


records:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The following PHP code selects all the rows from the persons table where
first_name='john':

Example
Procedural   Object Oriented   PDO

Download
<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Attempt select query execution

$sql="SELECT * FROM persons WHERE first_name='john'";

if($result=mysqli_query($link,$sql)){

if(mysqli_num_rows($result)>0){

echo"<table>";

echo"<tr>";
echo"<th>id</th>";

echo"<th>first_name</th>";

echo"<th>last_name</th>";

echo"<th>email</th>";

echo"</tr>";

while($row=mysqli_fetch_array($result)){

echo"<tr>";

echo"<td>".$row['id']."</td>";

echo"<td>".$row['first_name']."</td>";

echo"<td>".$row['last_name']."</td>";

echo"<td>".$row['email']."</td>";

echo"</tr>";

echo"</table>";

// Close result set

mysqli_free_result($result);
}else{

echo"No records matching your query were found.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
After filtration the result set will look something like this:
+----+------------+-----------+---------------------+

| id | first_name | last_name | email |

+----+------------+-----------+---------------------+

| 2 | John | Rambo | [email protected] |

| 4 | John | Carter | [email protected] |

+----+------------+-----------+---------------------+
Chapter 45

PHP MySQL LIMIT Clause
In this tutorial you will learn how to fetch limited number of records from a
MySQL database table using PHP.

Limiting Result Sets


The LIMIT clause is used to constrain the number of rows returned by
the SELECT statement. This feature is very helpful for optimizing the page loading
time as well as to enhance the readability of a website. For example you can
divide the large number of records in multiple pages using pagination, where
limited number of records will be loaded on every page from the database when
a user request for that page by clicking on pagination link.

The basic syntax of the LIMIT clause can be given with:


SELECT column_name(s) FROM table_name LIMIT row_offset, row_count;

The LIMIT clause accepts one or two parameters which must be a nonnegative


integer:

 When two parameters are specified, the first parameter specifies the offset
of the first row to return i.e. the starting point, whereas the second parameter
specifies the number of rows to return. The offset of the first row is 0 (not 1).
 Whereas, when only one parameter is given, it specifies the maximum
number of rows to return from the beginning of the result set.

For example, to retrieve the first three rows, you can use the following query:
SELECT * FROM persons LIMIT 3;

To retrieve the rows 2-4 (inclusive) of a result set, you can use the following
query:
SELECT * FROM persons LIMIT 1, 3;

Let's make a SQL query using the LIMIT clause in SELECT statement, after that we


will execute this query through passing it to the PHP mysqli_query() function to
get the limited number of records. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |


+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example will display just three rows from
the persons table.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());


}

// Attempt select query execution

$sql="SELECT * FROM persons LIMIT 3";

if($result=mysqli_query($link,$sql)){

if(mysqli_num_rows($result)>0){

echo"<table>";

echo"<tr>";

echo"<th>id</th>";

echo"<th>first_name</th>";

echo"<th>last_name</th>";

echo"<th>email</th>";

echo"</tr>";

while($row=mysqli_fetch_array($result)){

echo"<tr>";

echo"<td>".$row['id']."</td>";
echo"<td>".$row['first_name']."</td>";

echo"<td>".$row['last_name']."</td>";

echo"<td>".$row['email']."</td>";

echo"</tr>";

echo"</table>";

// Close result set

mysqli_free_result($result);

}else{

echo"No records matching your query were found.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection
mysqli_close($link);

?>
After limiting the result set the output will look something like this:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

+----+------------+-----------+----------------------+

Chapter 46

PHP MySQL ORDER BY Clause


In this tutorial you will learn how to sort and display the data from a MySQL table
in ascending or descending order using PHP.

Ordering the Result Set


The ORDER BY clause can be used in conjugation with the SELECT statement to see
the data from a table ordered by a specific field. The ORDER BY clause lets you
define the field name to sort against and the sort direction either ascending or
descending.

The basic syntax of this clause can be given with:


SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

Let's make a SQL query using the ORDER BY clause in SELECT statement, after that we
will execute this query through passing it to the PHP mysqli_query() function to
get the ordered data. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example selects all rows from the persons table
and sorts the result by the first_name column in the alphabetically ascending
order.

Example
Procedural   Object Oriented   PDO
Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Attempt select query execution with order by clause

$sql="SELECT * FROM persons ORDER BY first_name";

if($result=mysqli_query($link,$sql)){

if(mysqli_num_rows($result)>0){

echo"<table>";
echo"<tr>";

echo"<th>id</th>";

echo"<th>first_name</th>";

echo"<th>last_name</th>";

echo"<th>email</th>";

echo"</tr>";

while($row=mysqli_fetch_array($result)){

echo"<tr>";

echo"<td>".$row['id']."</td>";

echo"<td>".$row['first_name']."</td>";

echo"<td>".$row['last_name']."</td>";

echo"<td>".$row['email']."</td>";

echo"</tr>";

echo"</table>";

// Close result set


mysqli_free_result($result);

}else{

echo"No records matching your query were found.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
After ordering the result, the result set will look something like this:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 3 | Clark | Kent | [email protected] |

| 5 | Harry | Potter | [email protected] |

| 2 | John | Rambo | [email protected] |

| 4 | John | Carter | [email protected] |


| 1 | Peter | Parker | [email protected] |

+----+------------+-----------+----------------------+

Tip: By default the ORDER BY clause sort the results in ascending order. If you want
to sort the records in a descending order, you can use the DESC keyword.

Chapter 47

PHP MySQL UPDATE Query
In this tutorial you'll learn how to update the records in a MySQL table using PHP.
Updating Database Table Data
The UPDATE statement is used to change or modify the existing records in a
database table. This statement is typically used in conjugation with
the WHERE clause to apply the changes to only those records that matches specific
criteria.

The basic syntax of the UPDATE statement can be given with:


UPDATE table_name SET column1=value,
column2=value2,... WHERE column_name=some_value

Let's make a SQL query using the UPDATE statement and WHERE clause, after that we


will execute this query through passing it to the PHP mysqli_query() function to
update the tables records. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example will update the email address of a person
in the persons table whose id is equal to 1.

Example
Procedural   Object Oriented   PDO

Download
<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Attempt update query execution

$sql="UPDATE persons SET email='[email protected]' WHERE


id=1";

if(mysqli_query($link,$sql)){

echo"Records were updated successfully.";

}else{
echo"ERROR: Could not able to execute $sql.
".mysqli_error($link);

// Close connection

mysqli_close($link);

?>
After update the persons table will look something like this:
+----+------------+-----------+--------------------------+

| id | first_name | last_name | email |

+----+------------+-----------+--------------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+--------------------------+

Warning: The WHERE clause in the UPDATE statement specifies which record or


records should be updated. If you omit the WHERE clause, all records will be
updated.
Chapter 48

PHP MySQL DELETE Query
In this tutorial you'll learn how to delete records from a MySQL table using PHP.

Deleting Database Table Data


Just as you insert records into tables, you can delete records from a table using
the SQL DELETE statement. It is typically used in conjugation with the WHERE clause
to delete only those records that matches specific criteria or condition.

The basic syntax of the DELETE statement can be given with:


DELETE FROM table_name WHERE column_name=some_value

Let's make a SQL query using the DELETE statement and WHERE clause, after that we


will execute this query through passing it to the PHP mysqli_query() function to
delete the tables records. Consider the following persons table inside
the demo database:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example will delete the records of those persons
from the persons table whose first_name is equal to John.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL
server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

// Attempt delete query execution

$sql="DELETE FROM persons WHERE first_name='John'";

if(mysqli_query($link,$sql)){

echo"Records were deleted successfully.";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

}
// Close connection

mysqli_close($link);

?>
After the deletion the persons table will look something like this:
+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

As you can see the records has been deleted successfully from the persons table.

Warning: The WHERE clause in the DELETE statement specifies which record or


records should be deleted. If you omit the WHERE clause, all records will be deleted.

Chapter 49
PHP MySQL CRUD Application
In this tutorial you'll learn how to build a CRUD application with PHP and MySQL.

What is CRUD
CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are
basic data manipulation for database. We've already learned how to perform
create (i.e. insert), read (i.e. select), update and delete operations in previous
chapters. In this tutorial we'll create a simple PHP application to perform all these
operations on a MySQL database table at one place.
Well, let's start by creating the table which we'll use in all of our example.

Creating the Database Table


Execute the following SQL query to create a table named employees inside your
MySQL database. We will use this table for all of our future operations.

Example
Download

CREATETABLE employees (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
name VARCHAR(100)NOTNULL,
address VARCHAR(255)NOTNULL,
salary INT(10)NOTNULL
);

Creating the Config File


After creating the table, we need create a PHP script in order to connect to the
MySQL database server. Let's create a file named "config.php" and put the
following code inside it.

We'll later include this config file in other pages using the
PHP require_once() function.

Example
Procedural   Object Oriented   PDO

Download

<?php

/* Database credentials. Assuming you are running MySQL


server with default setting (user 'root' with no password) */

define('DB_SERVER','localhost');

define('DB_USERNAME','root');

define('DB_PASSWORD','');

define('DB_NAME','demo');

/* Attempt to connect to MySQL database */

$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

?>
If you've downloaded the Object Oriented or PDO code examples using the
download button, please remove the text "-oo-format" or "-pdo-format" from file
names before testing the code.

Note: Replace the credentials according to your MySQL server setting before


testing this code, for example, replace the database name 'demo' with your own
database name, replace username 'root' with your own database username,
specify database password if there's any.

Creating the Landing Page


First we will create a landing page for our CRUD application that contains a data
grid showing the records from the employees database table. It also has action
icons for each record displayed in the grid, that you may choose to view its
details, update it, or delete it.

We'll also add a create button on the top of the data grid that can be used for
creating new records in the employees table. Create a file named "index.php" and
put the following code in it:

Example
Procedural   Object Oriented   PDO

Download

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Dashboard</title>

<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.m
in.js"></script>

<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap
.js"></script>

<style type="text/css">

.wrapper{

width: 650px;

margin: 0 auto;

.page-header h2{

margin-top: 0;

table tr td:last-child a{

margin-right: 15px;

</style>

<script type="text/javascript">
$(document).ready(function(){

$('[data-toggle="tooltip"]').tooltip();

});

</script>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header clearfix">

<h2 class="pull-left">Employees Details</h2>

<a href="create.php"class="btn btn-success pull-right">Add New


Employee</a>

</div>

<?php

// Include config file


require_once"config.php";

// Attempt select query execution

$sql="SELECT * FROM employees";

if($result=mysqli_query($link,$sql)){

if(mysqli_num_rows($result)>0){

echo"<table class='table table-bordered table-striped'>";

echo"<thead>";

echo"<tr>";

echo"<th>#</th>";

echo"<th>Name</th>";

echo"<th>Address</th>";

echo"<th>Salary</th>";

echo"<th>Action</th>";

echo"</tr>";

echo"</thead>";
echo"<tbody>";

while($row=mysqli_fetch_array($result)){

echo"<tr>";

echo"<td>".$row['id']."</td>";

echo"<td>".$row['name']."</td>";

echo"<td>".$row['address']."</td>";

echo"<td>".$row['salary']."</td>";

echo"<td>";

echo"<a href='read.php?id=".$row['id']."' title='View Record'


data-toggle='tooltip'><span class='glyphicon glyphicon-eye-
open'></span></a>";

echo"<a href='update.php?id=".$row['id']."' title='Update Record'


data-toggle='tooltip'><span class='glyphicon glyphicon-
pencil'></span></a>";

echo"<a href='delete.php?id=".$row['id']."' title='Delete Record'


data-toggle='tooltip'><span class='glyphicon glyphicon-
trash'></span></a>";

echo"</td>";

echo"</tr>";

}
echo"</tbody>";

echo"</table>";

// Free result set

mysqli_free_result($result);

}else{

echo"<p class='lead'><em>No records were found.</em></p>";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close connection

mysqli_close($link);

?>

</div>

</div>
</div>

</div>

</body>

</html>
Once employees table is populated with some records the landing page i.e. the
CRUD data grid may look something like the picture shown below:

Tip: We've used the Bootstrap framework to make this CRUD application layout
quickly and beautifully. Bootstrap is the most popular and powerful front-end
framework for faster and easier responsive web development. Please, checkout
the Bootstrap tutorial section to learn more about this framework.

Creating the Create Page


In this section we'll build the Create functionality of our CRUD application.

Let's create a file named "create.php" and put the following code inside it. It will
generate a web form that can be used to insert records in the employees table.

Example
Procedural   Object Oriented   PDO

Download

<?php

// Include config file

require_once"config.php";

// Define variables and initialize with empty values

$name=$address=$salary="";

$name_err=$address_err=$salary_err="";

// Processing form data when form is submitted

if($_SERVER["REQUEST_METHOD"]=="POST"){

// Validate name

$input_name=trim($_POST["name"]);

if(empty($input_name)){

$name_err="Please enter a name.";


}elseif(!
filter_var($input_name,FILTER_VALIDATE_REGEXP,array("options"=>ar
ray("regexp"=>"/^[a-zA-Z\s]+$/")))){

$name_err="Please enter a valid name.";

}else{

$name=$input_name;

// Validate address

$input_address=trim($_POST["address"]);

if(empty($input_address)){

$address_err="Please enter an address.";

}else{

$address=$input_address;

// Validate salary
$input_salary=trim($_POST["salary"]);

if(empty($input_salary)){

$salary_err="Please enter the salary amount.";

}elseif(!ctype_digit($input_salary)){

$salary_err="Please enter a positive integer value.";

}else{

$salary=$input_salary;

// Check input errors before inserting in database

if(empty($name_err)&&empty($address_err)&&empty($salary_err)){

// Prepare an insert statement

$sql="INSERT INTO employees (name, address, salary) VALUES (?, ?,


?)";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters


mysqli_stmt_bind_param($stmt,"sss",$param_name,$param_address,
$param_salary);

// Set parameters

$param_name=$name;

$param_address=$address;

$param_salary=$salary;

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Records created successfully. Redirect to landing page

header("location: index.php");

exit();

}else{

echo"Something went wrong. Please try again later.";

}
// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Create Record</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">

<style type="text/css">

.wrapper{

width: 500px;

margin: 0 auto;

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h2>Create Record</h2>
</div>

<p>Please fill this form and submit to add employee record to the
database.</p>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?


>"method="post">

<div class="form-group <?php echo (!empty($name_err))?'has-


error':'';?>">

<label>Name</label>

<input type="text"name="name"class="form-control"value="<?php
echo $name;?>">

<span class="help-block"><?phpecho$name_err;?></span>

</div>

<div class="form-group <?php echo (!empty($address_err))?'has-


error':'';?>">

<label>Address</label>

<textarea name="address"class="form-control"><?phpecho$address;?
></textarea>

<span class="help-block"><?phpecho$address_err;?></span>

</div>

<div class="form-group <?php echo (!empty($salary_err))?'has-


error':'';?>">
<label>Salary</label>

<input type="text"name="salary"class="form-control"value="<?php
echo $salary;?>">

<span class="help-block"><?phpecho$salary_err;?></span>

</div>

<input type="submit"class="btn btn-primary"value="Submit">

<a href="index.php"class="btn btn-default">Cancel</a>

</form>

</div>

</div>

</div>

</div>

</body>

</html>
The same "create.php" file will display the HTML form and process the submitted
form data. It will also perform basic validation on user inputs (line no-11 to 37)
before saving the data.
Creating the Read Page
Now it's time to build the Read functionality of our CRUD application.

Let's create a file named "read.php" and put the following code inside it. It will
simply retrieve the records from the employees table based the id attribute of the
employee.

Example
Procedural   Object Oriented   PDO

Download

<?php

// Check existence of id parameter before processing further

if(isset($_GET["id"])&&!empty(trim($_GET["id"]))){

// Include config file

require_once"config.php";

// Prepare a select statement

$sql="SELECT * FROM employees WHERE id = ?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters


mysqli_stmt_bind_param($stmt,"i",$param_id);

// Set parameters

$param_id=trim($_GET["id"]);

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

$result=mysqli_stmt_get_result($stmt);

if(mysqli_num_rows($result)==1){

/* Fetch result row as an associative array. Since the result set


contains only one row, we don't need to use while loop */

$row=mysqli_fetch_array($result,MYSQLI_ASSOC);

// Retrieve individual field value

$name=$row["name"];

$address=$row["address"];
$salary=$row["salary"];

}else{

// URL doesn't contain valid id parameter. Redirect to error page

header("location: error.php");

exit();

}else{

echo"Oops! Something went wrong. Please try again later.";

// Close statement

mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);

}else{

// URL doesn't contain id parameter. Redirect to error page

header("location: error.php");

exit();

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>View Record</title>

<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">

<style type="text/css">

.wrapper{
width: 500px;

margin: 0 auto;

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h1>View Record</h1>

</div>

<div class="form-group">

<label>Name</label>

<p class="form-control-static"><?phpecho$row["name"];?></p>
</div>

<div class="form-group">

<label>Address</label>

<p class="form-control-static"><?phpecho$row["address"];?></p>

</div>

<div class="form-group">

<label>Salary</label>

<p class="form-control-static"><?phpecho$row["salary"];?></p>

</div>

<p><a href="index.php"class="btn btn-primary">Back</a></p>

</div>

</div>

</div>

</div>

</body>

</html>
Creating the Update Page
Similarly, we can build the Update functionality of our CRUD application.

Let's create a file named "update.php" and put the following code inside it. It will
update the existing records in the employees table based the id attribute of the
employee.

Example
Procedural   Object Oriented   PDO

Download

<?php

// Include config file

require_once"config.php";

// Define variables and initialize with empty values

$name=$address=$salary="";

$name_err=$address_err=$salary_err="";

// Processing form data when form is submitted


if(isset($_POST["id"])&&!empty($_POST["id"])){

// Get hidden input value

$id=$_POST["id"];

// Validate name

$input_name=trim($_POST["name"]);

if(empty($input_name)){

$name_err="Please enter a name.";

}elseif(!
filter_var($input_name,FILTER_VALIDATE_REGEXP,array("options"=>ar
ray("regexp"=>"/^[a-zA-Z\s]+$/")))){

$name_err="Please enter a valid name.";

}else{

$name=$input_name;

// Validate address address


$input_address=trim($_POST["address"]);

if(empty($input_address)){

$address_err="Please enter an address.";

}else{

$address=$input_address;

// Validate salary

$input_salary=trim($_POST["salary"]);

if(empty($input_salary)){

$salary_err="Please enter the salary amount.";

}elseif(!ctype_digit($input_salary)){

$salary_err="Please enter a positive integer value.";

}else{

$salary=$input_salary;

}
// Check input errors before inserting in database

if(empty($name_err)&&empty($address_err)&&empty($salary_err)){

// Prepare an update statement

$sql="UPDATE employees SET name=?, address=?, salary=? WHERE


id=?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"sssi",$param_name,$param_address,
$param_salary,$param_id);

// Set parameters

$param_name=$name;

$param_address=$address;

$param_salary=$salary;

$param_id=$id;
// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Records updated successfully. Redirect to landing page

header("location: index.php");

exit();

}else{

echo"Something went wrong. Please try again later.";

// Close statement

mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);

}else{

// Check existence of id parameter before processing further

if(isset($_GET["id"])&&!empty(trim($_GET["id"]))){

// Get URL parameter

$id=trim($_GET["id"]);

// Prepare a select statement

$sql="SELECT * FROM employees WHERE id = ?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"i",$param_id);

// Set parameters

$param_id=$id;
// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

$result=mysqli_stmt_get_result($stmt);

if(mysqli_num_rows($result)==1){

/* Fetch result row as an associative array. Since the result set


contains only one row, we don't need to use while loop */

$row=mysqli_fetch_array($result,MYSQLI_ASSOC);

// Retrieve individual field value

$name=$row["name"];

$address=$row["address"];

$salary=$row["salary"];

}else{

// URL doesn't contain valid id. Redirect to error page

header("location: error.php");

exit();
}

}else{

echo"Oops! Something went wrong. Please try again later.";

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

}else{

// URL doesn't contain id parameter. Redirect to error page

header("location: error.php");

exit();
}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Update Record</title>

<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">

<style type="text/css">

.wrapper{

width: 500px;

margin: 0 auto;

}
</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h2>Update Record</h2>

</div>

<p>Please edit the input values and submit to update the


record.</p>

<form action="<?php echo


htmlspecialchars(basename($_SERVER['REQUEST_URI']));?
>"method="post">

<div class="form-group <?php echo (!empty($name_err))?'has-


error':'';?>">

<label>Name</label>
<input type="text"name="name"class="form-control"value="<?php
echo $name;?>">

<span class="help-block"><?phpecho$name_err;?></span>

</div>

<div class="form-group <?php echo (!empty($address_err))?'has-


error':'';?>">

<label>Address</label>

<textarea name="address"class="form-control"><?phpecho$address;?
></textarea>

<span class="help-block"><?phpecho$address_err;?></span>

</div>

<div class="form-group <?php echo (!empty($salary_err))?'has-


error':'';?>">

<label>Salary</label>

<input type="text"name="salary"class="form-control"value="<?php
echo $salary;?>">

<span class="help-block"><?phpecho$salary_err;?></span>

</div>

<input type="hidden"name="id"value="<?php echo $id;?>"/>


<input type="submit"class="btn btn-primary"value="Submit">

<a href="index.php"class="btn btn-default">Cancel</a>

</form>

</div>

</div>

</div>

</div>

</body>

</html>

Creating the Delete Page


Finally, we will build the Delete functionality of our CRUD application.

Let's create a file named "delete.php" and put the following code inside it. It will
delete the existing records from the employees table based the id attribute of the
employee.

Example
Procedural   Object Oriented   PDO

Download
<?php

// Process delete operation after confirmation

if(isset($_POST["id"])&&!empty($_POST["id"])){

// Include config file

require_once"config.php";

// Prepare a delete statement

$sql="DELETE FROM employees WHERE id = ?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"i",$param_id);

// Set parameters

$param_id=trim($_POST["id"]);
// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Records deleted successfully. Redirect to landing page

header("location: index.php");

exit();

}else{

echo"Oops! Something went wrong. Please try again later.";

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

}else{
// Check existence of id parameter

if(empty(trim($_GET["id"]))){

// URL doesn't contain id parameter. Redirect to error page

header("location: error.php");

exit();

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>View Record</title>

<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">

<style type="text/css">
.wrapper{

width: 500px;

margin: 0 auto;

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h1>Delete Record</h1>

</div>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?


>"method="post">

<div class="alert alert-danger fade in">


<input type="hidden"name="id"value="<?php echo
trim($_GET["id"]);?>"/>

<p>Are you sure you want to delete this record?</p><br>

<p>

<input type="submit"value="Yes"class="btn btn-danger">

<a href="index.php"class="btn btn-default">No</a>

</p>

</div>

</form>

</div>

</div>

</div>

</div>

</body>

</html>
Creating the Error Page
At the end, let's create one more file "error.php". This page will be displayed if
request is invalid i.e. if id parameter is missing from the URL query string or it is
not valid.

Example
Download

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 750px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1>Invalid Request</h1>
</div>
<div class="alert alert-danger fade in">
<p>Sorry, you've made an invalid request. Please <a
href="index.php"class="alert-link">go back</a> and try again.</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
After a long journey finally we've finished our CRUD application with PHP and
MySQL. We recommend you to check out PHP & MySQL database tutorial
section from the beginning, if you haven't already covered, for a better
understanding of each and every part of this tutorial.

Chapter 48

PHP MySQL Ajax Live Search


In this tutorial you'll learn how to create a live MySQL database search feature
using PHP and Ajax.

Ajax Live Database Search


You can create a simple live database search functionality utilizing the Ajax and
PHP, where the search results will be displayed as you start typing some character
in search input box.

In this tutorial we're going to create a live search box that will search
the countries table and show the results asynchronously. But, first of all we need
to create this table.

Step 1: Creating the Database Table


Execute the following SQL query to create the countries table in your MySQL
database.

Example
Download

CREATETABLE countries (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
name VARCHAR(50)NOTNULL
);
After creating the table, you need to populate it with some data using
the SQL INSERT statement. Alternatively, you can download the
prepopulated countries table by clicking the download button and import it in
your MySQL database.

Please check out the tutorial on SQL CREATE TABLE statement for the detailed


information about syntax for creating tables in MySQL database system.

Step 2: Creating the Search Form


Now, let's create a simple web interface that allows user to live search the names
of countries available in our countries table, just like an autocomplete or
typeahead.

Create a PHP file named "search-form.php" and put the following code inside of
it.

Example
Download

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
/* Formatting search box */
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
/* Formatting result items */
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
</style>
<script src="https://code.jquery.com/jquery-
1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input",function(){
/* Get input value on change */
var inputVal =$(this).val();
var resultDropdown =$(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php",{term:
inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
}else{
resultDropdown.empty();
}
});

// Set search input value on click of result item


$(document).on("click",".result p",function(){
$(this).parents(".search-box").find('input[type="text"]').val($
(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box">
<input type="text"autocomplete="off"placeholder="Search
country..."/>
<div class="result"></div>
</div>
</body>
</html>
Every time the content of search input is changed or keyup event occur on search
input the jQuery code (line no-47 to 67) sent an Ajax request to the "backend-
search.php" file which retrieves the records from countries table related to the
searched term. Those records later will be inserted inside a <div> by the jQuery
and displayed on the browser.

Step 3: Processing Search Query in Backend


And here's the source code of our "backend-search.php" file which searches the
database based on query string sent by the Ajax request and send the results
back to browser.
Example
Procedural   Object Oriented   PDO

Download

<?php

/* Attempt MySQL server connection. Assuming you are running


MySQL

server with default setting (user 'root' with no password) */

$link=mysqli_connect("localhost","root","","demo");

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

if(isset($_REQUEST["term"])){

// Prepare a select statement

$sql="SELECT * FROM countries WHERE name LIKE ?";


if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"s",$param_term);

// Set parameters

$param_term=$_REQUEST["term"].'%';

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

$result=mysqli_stmt_get_result($stmt);

// Check number of rows in the result set

if(mysqli_num_rows($result)>0){

// Fetch result rows as an associative array

while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo"<p>".$row["name"]."</p>";

}else{

echo"<p>No matches found</p>";

}else{

echo"ERROR: Could not able to execute $sql.


".mysqli_error($link);

// Close statement

mysqli_stmt_close($stmt);

// close connection

mysqli_close($link);
?>
The SQL SELECT statement is used in combination with the LIKE operator (line no-
16) to find the matching records in countries database table. We've implemented
the prepared statement for better search performance as well as to prevent
the SQL injection attack.

Note: Always filter and validate user input before using it in a SQL statement. You
can also use PHP mysqli_real_escape_string() function to escape special characters
in a user input and create a legal SQL string to protect against SQL injection.

Chapter 49

PHP MySQL Login System


In this tutorial you will learn how to build a login system with PHP and MySQL.

Implementing User Authentication Mechanism


User authentication is very common in modern web application. It is a security
mechanism that is used to restrict unauthorized access to member-only areas
and tools on a site.
In this tutorial we'll create a simple registration and login system using the PHP
and MySQL. This tutorial is comprised of two parts: in the first part we'll create a
user registration form, and in the second part we'll create a login form, as well as
a welcome page and a logout script.

Building the Registration System


In this section we'll build a registration system that allows users to create a new
account by filling out a web form. But, first we need to create a table that will
hold all the user data.

Step 1: Creating the Database Table


Execute the following SQL query to create the users table inside your MySQL
database.

Example
Download

CREATETABLE users (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
username VARCHAR(50)NOTNULLUNIQUE,
password VARCHAR(255)NOTNULL,
created_at DATETIMEDEFAULTCURRENT_TIMESTAMP
);
Please check out the tutorial on SQL CREATE TABLE statement for the detailed
information about syntax for creating tables in MySQL database system.

Step 2: Creating the Config File


After creating the table, we need create a PHP script in order to connect to the
MySQL database server. Let's create a file named "config.php" and put the
following code inside it.

Example
Procedural   Object Oriented   PDO

Download
<?php

/* Database credentials. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

define('DB_SERVER','localhost');

define('DB_USERNAME','root');

define('DB_PASSWORD','');

define('DB_NAME','demo');

/* Attempt to connect to MySQL database */

$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);

// Check connection

if($link===false){

die("ERROR: Could not connect. ".mysqli_connect_error());

?>
If you've downloaded the Object Oriented or PDO code examples using the
download button, please remove the text "-oo-format" or "-pdo-format" from file
names before testing the code.

Note: Replace the credentials according to your MySQL server setting before


testing this code, for example, replace the database name 'demo' with your own
database name, replace username 'root' with your own database username,
specify database password if there's any.

Step 3: Creating the Registration Form


Let's create another PHP file "register.php" and put the following example code in
it. This example code will create a web form that allows user to register
themselves.

This script will also generate errors if a user tries to submit the form without
entering any value, or if username entered by the user is already taken by
another user.

Example
Procedural   Object Oriented   PDO

Download

<?php

// Include config file

require_once"config.php";

// Define variables and initialize with empty values

$username=$password=$confirm_password="";
$username_err=$password_err=$confirm_password_err="";

// Processing form data when form is submitted

if($_SERVER["REQUEST_METHOD"]=="POST"){

// Validate username

if(empty(trim($_POST["username"]))){

$username_err="Please enter a username.";

}else{

// Prepare a select statement

$sql="SELECT id FROM users WHERE username = ?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"s",$param_username);
// Set parameters

$param_username=trim($_POST["username"]);

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

/* store result */

mysqli_stmt_store_result($stmt);

if(mysqli_stmt_num_rows($stmt)==1){

$username_err="This username is already taken.";

}else{

$username=trim($_POST["username"]);

}else{

echo"Oops! Something went wrong. Please try again later.";

}
// Close statement

mysqli_stmt_close($stmt);

// Validate password

if(empty(trim($_POST["password"]))){

$password_err="Please enter a password.";

}elseif(strlen(trim($_POST["password"]))<6){

$password_err="Password must have atleast 6 characters.";

}else{

$password=trim($_POST["password"]);

// Validate confirm password


if(empty(trim($_POST["confirm_password"]))){

$confirm_password_err="Please confirm password.";

}else{

$confirm_password=trim($_POST["confirm_password"]);

if(empty($password_err)&&($password!=$confirm_password)){

$confirm_password_err="Password did not match.";

// Check input errors before inserting in database

if(empty($username_err)&&empty($password_err)&&empty($confirm_pas
sword_err)){

// Prepare an insert statement

$sql="INSERT INTO users (username, password) VALUES (?, ?)";

if($stmt=mysqli_prepare($link,$sql)){
// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"ss",$param_username,
$param_password);

// Set parameters

$param_username=$username;

$param_password=password_hash($password,PASSWORD_DEFAULT);//
Creates a password hash

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Redirect to login page

header("location: login.php");

}else{

echo"Something went wrong. Please try again later.";

}
// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Sign Up</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">

<style type="text/css">

body{font: 14px sans-serif;}

.wrapper{width: 350px;padding: 20px;}

</style>

</head>

<body>

<div class="wrapper">

<h2>Sign Up</h2>

<p>Please fill this form to create an account.</p>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?


>"method="post">

<div class="form-group <?php echo (!empty($username_err))?'has-


error':'';?>">

<label>Username</label>

<input type="text"name="username"class="form-control"value="<?php
echo $username;?>">
<span class="help-block"><?phpecho$username_err;?></span>

</div>

<div class="form-group <?php echo (!empty($password_err))?'has-


error':'';?>">

<label>Password</label>

<input type="password"name="password"class="form-
control"value="<?php echo $password;?>">

<span class="help-block"><?phpecho$password_err;?></span>

</div>

<div class="form-group <?php echo (!


empty($confirm_password_err))?'has-error':'';?>">

<label>Confirm Password</label>

<input type="password"name="confirm_password"class="form-
control"value="<?php echo $confirm_password;?>">

<span class="help-block"><?phpecho$confirm_password_err;?></span>

</div>

<div class="form-group">

<input type="submit"class="btn btn-primary"value="Submit">

<input type="reset"class="btn btn-default"value="Reset">


</div>

<p>Already have an account? <a href="login.php">Login


here</a>.</p>

</form>

</div>

</body>

</html>
— The output of the above example (i.e. signup form) will look something like
this:

In the above example, we've used the PHP password_hash() function to create


password hash from the password string entered by the user (line no-75). This
function creates a password hash using a strong one-way hashing algorithm. It
also generates and applies a random salt automatically when hashing the
password; this means that even if two users have the same passwords, their
password hashes will be different.

At the time of login we'll verify the given password with the password hash
stored in the database using the PHP password_verify() function, as demonstrated
in the next example.

We've used the Bootstrap framework to make the form layouts quickly and


beautifully. Please, checkout the Bootstrap tutorial section to learn more about
this framework.

Tip: Password salting is a technique which is widely used to secure passwords by


randomizing password hashes, so that if two users have the same password, they
will not have the same password hashes. This is done by appending or
prepending a random string, called a salt, to the password before hashing.

Building the Login System


In this section we'll create a login form where user can enter their username and
password. When user submit the form these inputs will be verified against the
credentials stored in the database, if the username and password match, the user
is authorized and granted access to the site, otherwise the login attempt will be
rejected.

Step 1: Creating the Login Form


Let's create a file named "login.php" and place the following code inside it.

Example
Procedural   Object Oriented   PDO

Download

<?php
// Initialize the session

session_start();

// Check if the user is already logged in, if yes then redirect


him to welcome page

if(isset($_SESSION["loggedin"])&&$_SESSION["loggedin"]===true){

header("location: welcome.php");

exit;

// Include config file

require_once"config.php";

// Define variables and initialize with empty values

$username=$password="";

$username_err=$password_err="";
// Processing form data when form is submitted

if($_SERVER["REQUEST_METHOD"]=="POST"){

// Check if username is empty

if(empty(trim($_POST["username"]))){

$username_err="Please enter username.";

}else{

$username=trim($_POST["username"]);

// Check if password is empty

if(empty(trim($_POST["password"]))){

$password_err="Please enter your password.";

}else{

$password=trim($_POST["password"]);

}
// Validate credentials

if(empty($username_err)&&empty($password_err)){

// Prepare a select statement

$sql="SELECT id, username, password FROM users WHERE username


= ?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"s",$param_username);

// Set parameters

$param_username=$username;

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Store result
mysqli_stmt_store_result($stmt);

// Check if username exists, if yes then verify password

if(mysqli_stmt_num_rows($stmt)==1){

// Bind result variables

mysqli_stmt_bind_result($stmt,$id,$username,$hashed_password);

if(mysqli_stmt_fetch($stmt)){

if(password_verify($password,$hashed_password)){

// Password is correct, so start a new session

session_start();

// Store data in session variables

$_SESSION["loggedin"]=true;

$_SESSION["id"]=$id;

$_SESSION["username"]=$username;
// Redirect user to welcome page

header("location: welcome.php");

}else{

// Display an error message if password is not valid

$password_err="The password you entered was not valid.";

}else{

// Display an error message if username doesn't exist

$username_err="No account found with that username.";

}else{

echo"Oops! Something went wrong. Please try again later.";

// Close statement
mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Login</title>

<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">

body{font: 14px sans-serif;}

.wrapper{width: 350px;padding: 20px;}

</style>

</head>

<body>

<div class="wrapper">

<h2>Login</h2>

<p>Please fill in your credentials to login.</p>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?


>"method="post">

<div class="form-group <?php echo (!empty($username_err))?'has-


error':'';?>">

<label>Username</label>

<input type="text"name="username"class="form-control"value="<?php
echo $username;?>">

<span class="help-block"><?phpecho$username_err;?></span>

</div>
<div class="form-group <?php echo (!empty($password_err))?'has-
error':'';?>">

<label>Password</label>

<input type="password"name="password"class="form-control">

<span class="help-block"><?phpecho$password_err;?></span>

</div>

<div class="form-group">

<input type="submit"class="btn btn-primary"value="Login">

</div>

<p>Don't have an account? <a href="register.php">Sign up


now</a>.</p>

</form>

</div>

</body>

</html>
— The output of the above example (i.e. login form) will look something like this:
Step 2: Creating the Welcome Page
Here's the code of our "welcome.php" file, where user is redirected after
successful login.

Example
Download

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to


login page
if(!isset($_SESSION["loggedin"])||$_SESSION["loggedin"]!==true){
header("location: login.php");
exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">
<style type="text/css">
body{font: 14px sans-serif;text-align: center;}
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?phpechohtmlspecialchars($_SESSION["username"]);?
></b>. Welcome to our site.</h1>
</div>
<p>
<a href="reset-password.php"class="btn btn-warning">Reset Your
Password</a>
<a href="logout.php"class="btn btn-danger">Sign Out of Your
Account</a>
</p>
</body>
</html>
If data comes from external sources like form filled in by anonymous users, there
is a risk that it may contain malicious script indented to launch cross-site scripting
(XSS) attacks. Therefore, you must escape this data using the
PHP htmlspecialchars() function before displaying it in the browser, so that any
HTML tag it contains becomes harmless.

For example, after escaping special characters the


string <script>alert("XSS")</script> becomes &lt;script&gt;alert("XSS")&lt;/script&
gt; which is not executed by the browser.

Step 3: Creating the Logout Script


Now, let's create a "logout.php" file. When the user clicks on the log out or sign
out link, the script inside this file destroys the session and redirect the user back
to the login page.

Example
Download

<?php
// Initialize the session
session_start();

// Unset all of the session variables


$_SESSION=array();

// Destroy the session.


session_destroy();

// Redirect to login page


header("location: login.php");
exit;
?>

Adding the Password Reset Feature


Finally, in this section we will add the password reset utility to our login system.
Using this feature logged in users can instantly reset their own password for their
accounts.

Let's create a file named "reset-password.php" and place the following code
inside it.

Example
Procedural   Object Oriented   PDO

Download

<?php

// Initialize the session

session_start();

// Check if the user is logged in, if not then redirect to login


page

if(!isset($_SESSION["loggedin"])||$_SESSION["loggedin"]!==true){
header("location: login.php");

exit;

// Include config file

require_once"config.php";

// Define variables and initialize with empty values

$new_password=$confirm_password="";

$new_password_err=$confirm_password_err="";

// Processing form data when form is submitted

if($_SERVER["REQUEST_METHOD"]=="POST"){

// Validate new password

if(empty(trim($_POST["new_password"]))){
$new_password_err="Please enter the new password.";

}elseif(strlen(trim($_POST["new_password"]))<6){

$new_password_err="Password must have atleast 6 characters.";

}else{

$new_password=trim($_POST["new_password"]);

// Validate confirm password

if(empty(trim($_POST["confirm_password"]))){

$confirm_password_err="Please confirm the password.";

}else{

$confirm_password=trim($_POST["confirm_password"]);

if(empty($new_password_err)&&($new_password!=$confirm_password)){

$confirm_password_err="Password did not match.";

}
// Check input errors before updating the database

if(empty($new_password_err)&&empty($confirm_password_err)){

// Prepare an update statement

$sql="UPDATE users SET password = ? WHERE id = ?";

if($stmt=mysqli_prepare($link,$sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt,"si",$param_password,$param_id);

// Set parameters

$param_password=password_hash($new_password,PASSWORD_DEFAULT);

$param_id=$_SESSION["id"];

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){
// Password updated successfully. Destroy the session, and
redirect to login page

session_destroy();

header("location: login.php");

exit();

}else{

echo"Oops! Something went wrong. Please try again later.";

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

}
?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Reset Password</title>

<link
rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3
.3.7/css/bootstrap.css">

<style type="text/css">

body{font: 14px sans-serif;}

.wrapper{width: 350px;padding: 20px;}

</style>

</head>

<body>

<div class="wrapper">
<h2>Reset Password</h2>

<p>Please fill out this form to reset your password.</p>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?


>"method="post">

<div class="form-group <?php echo (!


empty($new_password_err))?'has-error':'';?>">

<label>New Password</label>

<input type="password"name="new_password"class="form-
control"value="<?php echo $new_password;?>">

<span class="help-block"><?phpecho$new_password_err;?></span>

</div>

<div class="form-group <?php echo (!


empty($confirm_password_err))?'has-error':'';?>">

<label>Confirm Password</label>

<input type="password"name="confirm_password"class="form-
control">

<span class="help-block"><?phpecho$confirm_password_err;?></span>

</div>

<div class="form-group">
<input type="submit"class="btn btn-primary"value="Submit">

<a class="btn btn-link"href="welcome.php">Cancel</a>

</div>

</form>

</div>

</body>

</html>

You might also like