100% found this document useful (2 votes)
686 views149 pages

PHP Notes

PHP is a server-side scripting language designed for web development that allows developers to add dynamic and interactive elements to websites. It is open-source, runs on many platforms, and can be easily embedded into HTML. PHP code is interpreted on the server and outputs HTML that is then sent to the client. It is commonly used with a database like MySQL to build dynamic database-driven websites.

Uploaded by

Navaneet Knights
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (2 votes)
686 views149 pages

PHP Notes

PHP is a server-side scripting language designed for web development that allows developers to add dynamic and interactive elements to websites. It is open-source, runs on many platforms, and can be easily embedded into HTML. PHP code is interpreted on the server and outputs HTML that is then sent to the client. It is commonly used with a database like MySQL to build dynamic database-driven websites.

Uploaded by

Navaneet Knights
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 149

Overview of PHP

Full form of php is Hypertext Preprocessor. PHP is an intuitive, server side scripting language
and an interpreter designed for Web development, but also used as a general-purpose
programming language. Like any other scripting language it allows developers to build logic into
the creation of web page content and handle data returned from a web browser. PHP also
contains a number of extensions that make it easy to interact with databases, extracting data to be
displayed on a web page and storing information entered by a web site visitor back into the
database.

Like other scripting languages, PHP enables web developers to define the behavior and logic
they need in a web page. These scripts are embedded into the HTML documents that are served
by the web server. The interpreter takes the form of a module that integrates into the web server,
converting the scripts into commands the computer then executes to achieve the results defined
in the script by the web developer.

Features of php
It is most popular and frequently used worldwide scripting language, the main reason of
popularity is, It is open source and very simple and easy, this is widely used all over the world.
 Interpreted
It is an interpreted language, i.e. there is no need for compilation.
 Faster
It is faster than other scripting language e.g. asp and jsp.
 Open Source
Open source means you no need to pay for use php, you can free download and use.
 Platform Independent
PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.
 Case Sensitive
PHP is case sensitive scripting language at time of variable declaration. In PHP, all keywords
(e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-
sensitive.
 Error Reporting
PHP have some predefined error reporting constants to generate a warning or error notice.
 Real-Time Access Monitoring
PHP provides access logging by creating the summary of recent accesses for the user.
 Loosely Typed Language
PHP supports variable usage without declaring its data type. It will be taken at the time of the
execution based on the type of data it has on its value.

1
Uses of PHP

PHP is a scripting language generally used to make websites. PHP is mainly used for design
server side applications. Actually PHP is a server side scripting language which is used for
connect Web Page with a DataBase such as asp or jsp. Some basic uses of PHP are given below;

 It is used for create dynamic website.


 To Interact with web server (Apache etc)
 To interact with any back-end / database server e.g. MySQL
 It can Encrypt Data
 Access Cookies variable and set cookies
 Using php you can restrict user to access specific web page
 PHP usually used to output HTML code to the browser
 Used for connect web application with DataBase.
 It is used for send and receive E-Mails.

Advantages of PHP
 It runs on different platforms such as Windows, Linux, Unix, etc.
 This language is very simple to learn and runs efficiently on the server side.
 It is compatible with almost all servers used today,such as Apache, IIS, etc.
 It supports many databases such as MySQL, Oracle, PostgreSQL etc.
 It is perfectly suited for Web development and can be embedded directly into the HTML code.
 PHP can also be used to create dynamic web pages.
 It is often used together with Apache (web server) on various operating systems. It can be also used
with Microsoft's IIS on Windows.
 It is open source and it is free downloadable

What are static and dynamic Web pages?


Web pages can be either static or dynamic. "Static" means unchanged or constant, while
"dynamic" means changing or lively. Therefore, static Web pages contain the same prebuilt
content each time the page is loaded, while the content of dynamic Web pages can be generated
on-the-fly.

Standard HTML pages are static Web pages. They contain HTML code, which defines the
structure and content of the Web page. Each time an HTML page is loaded, it looks the same.
The only way the content of an HTML page will change is if the Web developer updates and
publishes the file.

Other types of Web pages, such as PHP, ASP, and JSP pages are dynamic Web pages. These
pages contain "server-side" code, which allows the server to generate unique content each time
the page is loaded. For example, the server may display the current time and date on the Web
page. It may also output a unique response based on a Web form the user filled out. Many

2
dynamic pages use server-side code to access database information, which enables the page's
content to be generated from information stored in the database - database-driven websites.

You can often tell if a page is static or dynamic simply by looking at the page's file extension in
the URL, located in the address field of the Web browser. If it is ".htm" or ".html," the page is
probably static. If the extension is ".php," ".asp," or ".jsp," the page is most likely dynamic.
While not all dynamic Web pages contain dynamic content, most have at least some content that
is generated on-the-fly.
Dynamic content from Databases
There are three main types of dynamic information on the Web:
 Dynamic data—Variables within a Web page are generated.
 Dynamic Web pages—An entire Web page is generated.
 Dynamic content—Portions of a Web page are generated.

PHP is a programming language designed to generate web pages interactively on the computer
serving them, which is called a web server. Unlike HTML, where the web browser uses tags and
markup to generate a page, PHP code runs between the requested page and the web server,
adding to and changing the basic HTML output.

PHP makes web development easy because all the code you need is contained within the PHP
framework. This means that there's no reason for you to reinvent the wheel each time you sit
down to develop a PHP program; it comes with web functionality built-in.
While PHP is great for web application development, it doesn't store information by itself. For
that, you need a database. The database of choice for PHP developers is MySQL, which acts like
a filing clerk for PHP-processed user information.

Developing Dynamic Internet Applications


“What is Web Development,” - Three parts of web development: client-side scripting, which is
a program that runs in a user’s web browser; server-side scripting, which runs on the web
server; and database technology, which manages all the information on the server

Basic web development languages


HTML and CSS are the two most basic web development languages, and are used to build nearly
all webpages on the Internet.

HTML is the standardized markup language that structures and formats content on the web.
Page elements like the titles, headings, text and links are included in the HTML document. It is
one of the core technologies in use on the Internet and serves as the backbone of all webpages.

CSS (Cascading Style Sheets) is a style-sheet language. Paired with HTML, CSS allows a
programmer to define the look and format of multiple webpages at once; elements like color,
layout and fonts are specified in one file that’s kept separate from the core code of the webpage.
These two languages provide the basic structure and style information used to create a static
webpage — a page that looks the same to everyone who visits it. Many webpages now are

3
dynamic webpages, which are slightly tailored to each new visitor. To create these more complex
webpages, you need to add more advanced client-side and server-side scripting.

Client-side scripting which includes HTML and CSS — is any code that runs within a web
browser. This means that the web browser temporarily downloads all the files from a web server
and, in turn, displays a static web page; you would be able to view these files even if you lost
your Internet connection (as long as you left your web browser open). JavaScript and
ActionScript (ActionScript is the language used for Adobe Flash, which is especially well suited
for rich Internet applications that use Flash animation and streaming audio and video) are the two
most commonly used client-side scripts.

JavaScript is the programming language that brings animation, games, apps, interactivity and
other dynamic effects to life. After HTML and CSS, it’s the most ubiquitous of the client-side
scripts. Some JavaScript applications can even run without connecting back to a web server,
which means they’ll work in a browser with or without an Internet connection.

Server-Side Scripting All websites need to be hosted (i.e. stored) in a database on a web server.
Server-side scripting simply refers to any code that facilitates the transfer of data from that web
server to a browser. It also refers to any code used to build a database or manage data on the web
server itself. Server-side scripts run on the web server, which has the power and resources to run
programs that are too resource intensive to be run by a web browser. Server-side scripts are also
more secure, because the source code remains on the web server rather than being temporarily
stored on an individual’s computer.

How to Install PHP Server


To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available Open Source in the
market that are given below:

 WAMP for Windows


 LAMP for Linux
 MAMP for Mac
 XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, OpenSSL, Mercury Mail etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh. Installing
PHP on your development PC allows you to safely create and test a web application without
affecting the data or systems on your live website.

4
PHP.INI file Configuration

The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's
functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd
is restarted for the module version or with each script execution for the CGI version. If your
change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use
phpinfo() to check the path to php.ini.

The configuration file is well commented and thorough. Keys are case sensitive, keyword values
are not; whitespace, and lines beginning with semicolons are ignored. Booleans can be
represented by 1/0, Yes/No, On/Off, or True/False. The default values in php.ini-dist will result
in a reasonable PHP installation that can be tweaked later.

Here we are explaining the important settings in php.ini which you may need for your PHP
Parser.

short_open_tag = Off
Short open tags look like this: <? ?>. This option must be set to Off if you want to use XML
functions.

max_execution_time = 30
The function set_time_limit() won.t work in safe mode, so this is the main way to make a script
time out in safe mode. In Windows, you have to abort based on maximum memory consumed
rather than time. You can also use the Apache timeout setting to timeout if you use Apache, but
that will apply to non-PHP files on the site too.

error_reporting = E_ALL & ~E_NOTICE


The default value is E_ALL & ~E_NOTICE, all errors except notices. Development servers
should be set to at least the default; only production servers should even consider a lesser value

register_globals = Off
This setting allows you to decide whether you wish to register EGPCS variables as global. This
is now deprecated, and as of PHP4.2, this flag is set to Off by default. Use superglobal arrays
instead. All the major code listings in this book use superglobal arrays.

magic_quotes_gpc = On
This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of forms
which possibly submit to themselves or other forms and display form values, you may need to
set this directive to On or prepare to use addslashes() on string-type data.

doc_root = [DIR]
If you are using Apache, you’ve already set a document root for this server or virtual host in
httpd.conf.

5
file_uploads = [on/off]
Turn on this flag if you will upload files using PHP script.

upload_tmp_dir = [DIR]
Do not uncomment this line unless you understand the implications of HTTP uploads!

PHP vs. ASP


PHP is a programming language whereas ASP.NET is a programming framework. Websites
developed by ASP.NET may use C#, but also other languages such as J#. ASP.NET is compiled
whereas PHP is interpreted. ... ASP.NET is designed for windows machines, whereas PHP is
platform free (and typically runs on Linux servers).

Basic syntax of PHP

The most universally effective PHP tag style is − <?php...?>

If you use this style, you can be positive that your tags will always be correctly interpreted.

Short-open (SGML-style) tags

Short or short-open tags look like this −

<?...?>

Short tags are, as one might expect, the shortest option You must do one of two things to enable
PHP to recognize the tags −

 Choose the --enable-short-tags configuration option when you're building PHP.


 et the short_open_tag setting in your php.ini file to on. This option must be disabled to
parse XML with PHP because the same syntax is used for XML tags.

ASP-style tags

ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style
tags look like this −

<%...%>

To use ASP-style tags, you will need to set the configuration option in your php.ini file.

6
HTML script tags

HTML script tags look like this −

<script language = "PHP">...</script>

Commenting PHP Code

A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP −

Single-line comments − They are generally used for short explanations or notes relevant to the
local code. Here are the examples of single line comments.

<?
# This is a comment, and
# This is the second line of the comment

// This is a comment too. Each style comments only


print "An example with single line comments";
?>

Multi-lines comments − They are generally used to provide pseudocode algorithms and more
detailed explanations when necessary. The multiline style of commenting is the same as in C.
Here are the example of multi lines comments.

<?
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
?>

How Does PHP Work?


To develop an understanding of how PHP works it is helpful to first explore what happens when
a web page is served to a user's browser.

When a user visits a web site or clicks on a link on a page the browser sends a request to the web
server hosting the site asking for a copy of the web page. The web server receives the request,

7
finds the corresponding web page file on the file system and sends it back, over the internet, to
the user's browser.

Typically the web server doesn't pay any attention to the content of the file it has just transmitted
to the web browser. As far as the web server is concerned the web browser understands the
content of the web page file and knows how to interpret and render it so that it appears as the
web designer intended.

Now let's consider what kind of web page content a web browser understands. These days a web
page is likely to consist of HTML, XHTML and JavaScript. The web browser contains code that
tells it what to do with these types of content. For example, it understands the structure HTML in
terms of rendering the page and it has a JavaScript interpreter built in that knows how to execute
the instructions in a JavaScript script. A web browser, however, knows absolutely nothing about
any PHP script that may be embedded in an HTML document. If a browser was served a web
page containing PHP it would not know how to interpret that code.

Given that a web browser knows nothing about PHP in a web page, then clearly something has to
be done with any PHP script in the page before it reaches the browser. This is where the PHP
pre-processing module comes in. The PHP module is, as mentioned previously, integrated into
the web server. The module tells the web server that when a page is to be served which contains
PHP script (identified by special markers) that it is to pass that script to the PHP pre-processing
module and wait for the PHP module to send it some content to replace that script fragment. The
PHP processing module understands PHP, executes the PHP script written by the web developer
and, based on the script instructions, creates output that the browser will understand. The web
server substitutes the content provided by the PHP pre-processor module in place of the PHP
script in the web page and sends it to the browser where it is rendered for the user to view.

To help understand this concept let's take a quick look at a before and after scenario. The
following HTML contains some PHP script that is designed to output an HTML paragraph tag:

<html>
<head>
<title>A PHP Example</title>
</head>
<body>

<?php
echo '<p>This line of HTML was generated by a PHP script embedded into an HTML document</p>';
?>

</body>
</html>

8
The above example looks very much like standard HTML until you reach the part surrounded by
<?php and ?>. These are markers that designate where the embedded PHP script begins and
ends. When the web server finds this it sends it to the PHP module. The PHP module interprets
it, converts it to HTML and sends it back to the web server. The web server, in turn, sends the
following to the browser:

<html>
<head>
<title>A PHP Example</title>
</head>
<body>

<p>This line of HTML was generated by a PHP script embedded into an HTML document</p>

</body>
</html>

Once loaded into the browser, it is rendered just like any other web page. The fact that the web
page originally contained PHP is completely transparent to the web browser.
PHP echo and print Statements
In PHP there are two basic ways to get output: echo and print. echo and print are more or less the
same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
Primitive data types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes

9
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
 An integer must have at least one digit
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based -
prefixed with 0x) or octal (8-based - prefixed with 0)
PHP Float
 A float (floating point number) is a number with a decimal point or a number in
exponential form.
 In the following example $x is a float. The PHP var_dump() function returns the data
type and value:
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods

PHP NULL Value


Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.

10
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:

PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.
A common example of using the resource data type is a database call.

PHP Variables

A variable is a holder for a type of data. So, based on its type, a variable can hold numbers,
strings, booleans, objects, resources or it can be NULL. In PHP all the variables begin with a
dollar sign "$" and the value can be assignes using the "=" operator. The dollar sign is not
technically part of the variable name, but it is required as the first character for the PHP parser to
recognize the variable as such.

Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP
we needn't have to specify the variable type, as it takes the data type of the assigned value. The
contents of a variable can be changed at any time, and so can its type. To declare a variable, you
must include it in your script. You can declare a variable and assign it a value in the same
statement.

Here is some code creating and assigning values to a couple of variables:

<?php
//Commented lines starting with the double forward slash will be ignored by PHP

//First we will declare a few variables and assign values to them

$myText = "Have a nice day!";


$myNum = 5;
//Note that myText is a string and myNum is numeric.

//Next we will display these to the user.


echo $myText;

//To concatenate strings in PHP, use the '.' (period) operator


echo "My favourite number is ". $myNum
?>

The output is: Have a nice day! My favourite number is 5.

Case Sensitivity

11
One thing that causes many problems and take hours of finding mistakes is case sensitivity. PHP
is case sensitive. Have a look at the following code:

<?php
$myVar = "WebCheatSheet";
$myvar = "PHP tutorial";

echo "$myVar - $myvar"; //outputs "WebCheatSheet - PHP tutorial"


?>

PHP Variable Naming Conventions

There are a few rules that you need to follow when choosing a name for your PHP variables.

 PHP variables must start with a letter or underscore "_".


 PHP variables may only be comprised of alpha-numeric characters and underscores. a-z,
A-Z, 0-9, or _ .
 Variables with more than one word should be separated with underscores: $my_variable.
 Variables with more than one word can also be distinguished with capitalization:
$myVariable.

One important thing to note if you are coming from another programming language there is no
size limit for variables.

PHP Constants

Constants just as variables are used to store information. The main difference between constants
and variables is that constant value can not be changed in the process of running program. It can
be mathematic constants, passwords, paths to files, etc. By using a constant you "lock in" the
value which prevents you from accidentally changing it. If you want to run a program several
times using a different value each time, you do not need to search throughout the entire program
and change the value at each instance. You only need to change it at the beginning of the
program where you set the initial value for the constant.

Have a look at the example where we use the define function to set the initial value of a constant:

<?php
// first we define a constant PASSWORD
define("PASSWORD","admin");

echo (PASSWORD); // will display value of PASSWORD constant, i.e. admin


echo constant("PASSWORD"); // will also display admin
echo "PASSWORD"; // will display PASSWORD
?>

12
PHP also provides a number of built-in constants for you. "__FILE__", for example, returns the
name of the file currently being read by the interpreter. "__LINE__" returns the line number of
the file. These constants are useful for generating error messages.

PHP Conditional Constructs

Sometimes when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this. Conditional statements are the set of
commands used to perform different actions based on different conditions. In this tutorial we will
look at two structures: if...else and switch statements. Both perform in saw way the same task.

 IF ... Else Statement


 Switch Statement

If ... Else Statement

The If Statement is a way to make decisions based upon the result of a condition. For example,
you might have a script that checks if boolean value is true or false, if variable contains number
or string value, if an object is empty or populated, etc. The condition can be anything you
choose, and you can combine conditions together to make for actions that are more complicated.

Use the if statement to execute a statement if a logical condition is true. Use the optional else
clause to execute a statement if the condition is false. The syntax for If statement looks as
follows:
if (condition) {
statements_1
} else {
statements_2
}
Condition can be any expression that evaluates to true or false. If condition evaluates to true,
statements_1 are executed; otherwise, statements_2 are executed. statement_1 and statement_2
can be any statement, including further nested if statements.

You may also compound the statements using elseif to have multiple conditions tested in
sequence. You should use this construction if you want to select one of many sets of lines to
execute.

if (condition_1) {
statement_1
}
[elseif (condition_2) {
statement_2
}]
...
[elseif (condition_n_1) {

13
statement_n_1
}]
[else {
statement_n
}]
Let's have a look at the examples. The first example decides whether a student has passed an
exam with a pass mark of 57:
<?php
$result = 70;

if ($result >= 57) {


echo "Pass <br />";
}
else {
echo "Fail <br />";
}
?>

Next example use the elseif variant on the if statement. This allows us to test for other conditions
if the first one wasn't true. The program will test each condition in sequence until:

 It finds one that is true. In this case it executes the code for that condition.
 It reaches an else statement. In which case it executes the code in the else statement.
 It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement
after the conditional structure.

<?php
$result = 70;

if ($result >= 75) {


echo "Passed: Grade A <br
/>";
}
elseif ($result >= 60) {
echo "Passed: Grade B <br
/>";
}
elseif ($result >= 45) {
echo "Passed: Grade C <br
/>";
}
else {
echo "Failed <br />";
}

14
?>

Switch Statement

Switch statements work the same as if statements. However the difference is that they can check
for multiple values. Of course you do the same with multiple if..else statements, but this is not
always the best approach.

A switch statement allows a program to evaluate an expression and attempt to match the
expression's value to a case label. If a match is found, the program executes the associated
statement. The syntax for the switch statement as follows:

switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_n
[break;]
}

The program first looks for a case clause with a label matching the value of expression and then
transfers control to that clause, executing the associated statements. If no matching label is
found, the program looks for the optional default clause, and if found, transfers control to that
clause, executing the associated statements. If no default clause is found, the program continues
execution at the statement following the end of switch. Use break to prevent the code from
running into the next case automatically.

Let's consider an example:

<?php
$flower = "rose";

switch ($flower)
{
case "rose" :
echo $flower." costs $2.50";
break;
case "daisy" :
echo $flower." costs $1.25";
break;
case "orchild" :

15
echo $flower." costs $1.50";
break;
default :
echo "There is no such flower in our shop";
break;
}
?>
PHP Loop Constructs
Loop constructs are used in programming to execute the same program statement or block of
code for a given number of times (or iterations), or until some exit condition has been satisfied.
An exit condition is something that must be true in order for the program to stop executing the
code contained within the body of the loop, and continue on to the next part of the program. PHP
has a number of loop constructs, which are briefly described below.

 while - executes a program statement or block of code repeatedly, as long as a given variable or
expression evaluates to TRUE. The exit condition is met when the variable or expression
evaluates to FALSE. If the exit condition evaluates to FALSE when program execution enters the
loop, the loop is exited immediately and none of the code inside the loop is executed.
 do...while - executes a program statement or block of code at least once, then continues to do so
providing a given variable or expression evaluates to TRUE. The exit condition is met when the
variable or expression evaluates to FALSE.
 for - executes a program statement or block of code a specified number of times (note that there
may be an exit condition that, if satisfied, terminates execution of the loop early).
 foreach - executes a program statement or block of code once for each element in an array (as
with the for loop, that there may be an exit condition that, if satisfied, terminates execution of the
loop early).

The short program below demonstrates the use of the while loop construct.

<html>
<body>
<?php
$num=1;
while($num <= 10)
{
// this code comprises the "body" of the loop
echo $num . " squared is: " . $num * $num . "<br>";
$num++;
}
?>
</body>
</html>

Enter the code above into a text editor and save it with the filename "while.php" in the "htdocs"
directory of your "xampp" directory. Run the XAMPP server, then type the following URL into
the browser's address bar:

16
http://localhost/while.php

The short script below demonstrates the use of the do-while loop construct. Note that this script
does exactly the same thing as the previous script. It just does it in a slightly different way (note
that for this version of the script, if you set the initial value of $num to a value greater than 10,
the loop will still execute once).

<html>
<body>
<?php
$num=1;
do
{
echo $num . " squared is: " . $num * $num . "<br>";
$num++;
}
while($num <= 10)
?>

</body>
</html>

Enter the code above into a text editor and save it with the filename "do_while.php" in the
"htdocs" directory of your "xampp" directory. Run the XAMPP server, then type the following
URL into the browser's address bar:

http://localhost/do_while.php

The For Loop

The For statement loop is used when you know how many times you want to execute a statement
or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of
For loops is a bit more complex, though for loops are often more convenient than While loops.
The For loop syntax is as follows:

for (initialization; condition; increment)


{
code to be executed;
}

The For statement takes three expressions inside its parentheses, separated by semi-colons. When
the For loop executes, the following occurs:

 The initializing expression is executed. This expression usually initializes one or more
loop counters, but the syntax allows an expression of any degree of complexity.

17
 The condition expression is evaluated. If the value of condition is true, the loop
statements execute. If the value of condition is false, the For loop terminates.
 The update expression increment executes.
 The statements execute, and control returns to step 2.

Have a look at the very simple example that prints out numbers from 0 to 10:

<?php
for ($i=0; $i <= 10; $i++)
{
echo "The number is ".$i."<br />";
}
?>

Next example generates a multiplication table 2 through 9. Outer loop is responsible for
generating a list of dividends, and inner loop will be responsible for generating lists of dividers
for each individual number:

<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";

for ($i = 1; $i <= 9; $i++ ) { //this is the outer loop


echo "<tr>";
echo "<td>".$i."</td>";

for ( $j = 2; $j <= 9; $j++ ) { // inner loop


echo "<td>".$i * $j."</td>";
}

echo "</tr>";
}

echo "</table>";
?>

The Foreach Loop

The Foreach loop is a variation of the For loop and allows you to iterate over elements in an
array. There are two different versions of the Foreach loop. The Foreach loop syntaxes are as
follows:

foreach (array as value)


{
code to be executed;
}

18
foreach (array as key => value)
{
code to be executed;
}

The example below demonstrates the Foreach loop that will print the values of the given array:

<?php
$email = array('john.smith@example.com', 'alex@example.com');
foreach ($email as $value) {
echo "Processing ".$value."<br />";
}
?>

PHP executes the body of the loop once for each element of $email in turn, with $value set to the
current element. Elements are processed by their internal order. Looping continues until the
Foreach loop reaches the last element or upper bound of the given array.

An alternative form of Foreach loop gives you access to the current key:

<?php
$person = array('name' => 'Andrew', 'age' => 21, 'address' => '77, Lincoln st.');
foreach ($person as $key => $value) {
echo $key." is ".$value."<br />";
}
?>

In this case, the key for each element is placed in $key and the corresponding value is placed in
$value.

The Foreach construct does not operate on the array itself, but rather on a copy of it. During each
loop, the value of the variable $value can be manipulated but the original value of the array
remains the same.

Break and Continue Statements

Sometimes you may want to let the loops start without any condition, and allow the statements
inside the brackets to decide when to exit the loop. There are two special statements that can be
used inside loops: Break and Continue.

The Break statement terminates the current While or For loop and continues executing the code
that follows after the loop (if any). Optionally, you can put a number after the Break keyword
indicating how many levels of loop structures to break out of. In this way, a statement buried
deep in nested loops can break out of the outermost loop.

19
Examples below show how to use the Break statement:

<?php
echo "<p><b>Example of using the Break statement:</b></p>";

for ($i=0; $i<=10; $i++) {


if ($i==3){break;}
echo "The number is ".$i;
echo "<br />";
}

echo "<p><b>One more example of using the Break statement:</b><p>";

$i = 0;
$j = 0;

while ($i < 10) {


while ($j < 10) {
if ($j == 5) {break 2;} // breaks out of two while loops
$j++;
}
$i++;
}

echo "The first number is ".$i."<br />";


echo "The second number is ".$j."<br />";
?>

The Continue statement terminates execution of the block of statements in a While or For loop
and continues execution of the loop with the next iteration:

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";

for ($i=0; $i<=10; $i++) {


if (i==3){continue;}
echo "The number is ".$i;
echo "<br />";
}
?>
PHP Operators
Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

20
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators

The PHP logical operators are used to combine conditional statements. The Operators are && (and), ||
(or) and !(Not).

PHP has two string operators: . (Concatenation) and .=( Concatenation Assignment)

The PHP Array operators are used to compare arrays.

Operator Name Example Result


+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of
the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP ternary operator


An essential part of programming is evaluating conditions using if/else and switch/case
statements. If / Else statements are easy to code and global to all languages. If / Else statements
are great but they can be too long. Using a conditional (if/then/else), it would look like this:
if( $valid ) {
$x = 'yes';
} else {
$x = 'no';
}
That should be pretty easy to read. If $valid is true set $x to yes, otherwise set it to no. But this
example is rather long for such a simple assignment. Ternary operator logic is the process of
using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else
structures. Let's do the above in one line with ternary logic:

$x = $valid ? 'yes' : 'no';

This produces the same result as before, but it's much shorter.

21
PHP Timestamp
PHP provides several date time functions to perform required operations with temporal data. The
timestamp is the value represented as seconds calculated, since UNIX Epoch, January 1, 1970,
and also called as UNIX timestamp. In PHP, it includes several functions to work with a
timestamp like:
 getting current timestamp
 date/time to timestamp conversion
Getting Current Timestamp in PHP
We can get current timestamp value in three possible ways with the help of PHP core functions..
time()
This is the simple and widely used PHP function to get current timestamp value. It requires no
arguments to be sent for returning expected resultant UNIX timestamp. The usage of this simple
function is shown in the example PHP program below.
<?php
$current_timestamp = time();
echo $current_timestamp;
?>
strtotime()
This function is mainly used to get timestamp value from the given string representing date
value. PHP provides a list of supported strings to be passed as an argument of this function to
denote date values. For example, “Tuesday last week”, “+1 week”, “21 November 2008” and etc.

similarly, for getting current timestamp value, we need to provide the string as “now”
representing current date and time value. So, the code will be as follows.

<?php
$current_timestamp = strtotime("now");
echo $current_timestamp;
?>
While invoking strtotime() by passing improper string data which is not supported by PHP, this
function will return false.
mktime()
This function is also used to get UNIX timestamp but requires set of parameters denoting date
components, like an hour, minute, second, month, day, year, in the same order specified here.
And also have an optional flag representing daylight saving time state.

And for getting, the current timestamp, we have to use the PHP date() function within this
function, with the corresponding parameter for getting the current hour, minute, in required
order. For example,

22
<?php
$current_timestamp_by_mktime = mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
echo $current_timestamp_by_mktime;
?>
date()
PHP supports several date format characters denoting components of the date value. So, we can
use these lists of date formatting characters to get date components or to format date if required,
using given temporal data.
From the list of those string, U denotes UNIX timestamp value. So, for date() function, we
should specify U as an argument to get current timestamp value. For example,
<?php
$current_timestamp_fndate = date("U");
echo $current_timestamp_fndate;
?>

Date/Time to Timestamp Conversion


strtotime() and mktime() functions are also used to convert specified date into the form of a
timestamp.

For using strtotime(), we need to pass the date with any one of PHP supported date format, for
example, dd/mm/yyyy, mm/dd/yyyy and etc. And, for using mktime(), we need to explode the
given date and send the exploded components to this function.

And, we can perform the reverse, that is, converting timestamp value to date, by the use of date()
function. For that, we should specify the required date format as the first parameter, and
timestamp as the second one. For example,

<?php
$date_from_timestamp = date("d-m-Y",$current_timestamp);
echo "Formatted date from timestamp:" . $date_from_timestamp;
?>
ARRAYS
Arrays can be used in many ways to store and organize data quickly and efficiently. It is one of
the more useful data types available to any programming language.

Arrays can most easily be described as an ordered list of elements. You can access the individual
elements by referring to their index position within the array. The position is either specified
numerically or by name. An array with a numeric index is commonly called an indexed array
while one that has named positions is called an associative array. In PHP, all arrays are
associative, but you can still use a numeric index to access them.

23
An Array is a PHP datatype used to store a group of data into a variable. Each array item is
stored as a key and value pair. Arrays are classified as “indexed array” and “associative array”
based on the key specification. The Indexed array has default index starts with ‘0’ and the
associative array contains the user-defined key index. The array can also be classified as “one-
dimensional array” and “multi-dimensional array” based on the level of the array index. In this
tutorial, we are going to see some of the important array functions in PHP.

An Example of an indexed Array:

<?php
$seven = 7;
$arrayname = array( "this is an element", 5, $seven );

echo $arrayname[0]; //prints: this is an element


echo $arrayname[1]; //prints: 5
echo $arrayname[2]; //prints: 7
?>

As you can see, elements in an array can be any type of data (string, integer, double) and can also
be other variables. An individual array element can be of any type, including another array.If you
want to find out if a variable contains an array you can use the is_array() function. Notice that
Indexed arrays start at position zero, not at position one, so your first array element has an index
of 0, and the highest position in the array is one less than the number of elements in the array.
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them. Have a look at the
following example:

<?php
$first_array = array("key1" => "the first element", "key2" => "the second element");

$second_array = array(
"key3" => "this is the first element of the second array",
"key4" => "this is the second element of the second array",
);
echo $first_array['key1']; //prints "the first element."
echo $second_array['key3']; //prints "the first element of the second array"
echo $first_array['key2']; //prints "the second element"
echo $second_array['key4']; //prints "this is the second element of the second array"
?>

Right, now you know how to define an associative array, but you probably don't see yet
how useful are they. Well think of this, say you have a flower-shop. You have 3 different
flowers, and each flower has a different price. Let's make this example in php.
24
<?php
//We initialize the array using the array() function.
//Note that for readability one can spread the argument over several lines.
$flower_shop = array (
"rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00"
);
echo "rose costs $flower_shop['rose'], daisy costs $flower_shop['daisy'], and orchild costs
$flower_shop['orchild'].";
?>
Because the indices in this associative array are not numbers, we cannot use a simple counter in a
for loop to work with the array. We can use the foreach loop. In the following example we use
the foreach loop to iterate through our flowers_shop array, and read them into a table. Note
carefully the syntax.
<?php
//We initialize the array using the array() function.
//Note that for readability one can spread the argument over several lines.
$flower_shop = array (
"rose" => "5.00",
"daisy" => "4.00",
"orchid" => "2.00",
);
//let's print out the headers to our table
echo "<table border='1' cellpadding='5'>";
echo"<tr><th>Flower</th><th>Price</th></tr>";
//Now we start the foreach loop using the variable $flower to hold our key
//and $price to hold our cost.
foreach($flower_shop as $Flower=>$Price)
{
echo "<tr><td>$Flower </td><td>$Price</td></tr> "; //print the values into a table cell for each
iteration
}
//finally close the table
echo "</table>";
?>
Multidimensional Arrays
In preceding example you've learned how to use arrays. But what if you want to give more
information on each flower? You now have the cost, but what if you wanted to add the number
of flowers you get for that price, and the colour of the flower? One of the ways to do it is using
multidimensional arrays.

25
A multidimensional array is an array that contains at least one other array as the value of one of
the indexes. Example below shows how to use multidimensional array:

<?php
//Initialize the array using the array() function.
$flower_shop = array(
"rose" => array( "5.00", "7 items", "red" ),
"daisy" => array( "4.00", "3 items", "blue" ),
"orchid" => array( "2.00", "1 item", "white" ),
);
//print "rose costs 5.00, and you get 7 items."
echo "rose costs ".$flower_shop['rose'][0].", and you get ".$flower_shop['rose'][1].".";
//print "daisy costs 4.00, and you get 3 items."
echo "daisy costs ".$flower_shop['daisy'][0].", and you get ".$flower_shop['daisy'][1].".";
//print "orchild costs 2.00, and you get 1 item.
echo "orchid costs ".$flower_shop['orchid'][0].", and you get ".$flower_shop['orchild'][1].".";
?>

ARRAY FUNCTIONS
is_array($arr); function is used to find whether a variable is an array or not Return True/False

Function Explanation Example


sizeof($arr) This function returns the Code:
number of elements in an $data = array("red", "green", "blue");
count($arr) array.
echo "Array has " . sizeof($data) . "
Use this function to find out elements";
how many elements an array ?>
contains; this information is
most commonly used to Output:
initialize a loop counter Array has 3 elements
when processing the array.
array_pop($arr) This function removes an Code:
element from the end of an $data = array("Donald", "Jim");
array. array_pop($data);
print_r($data);
?>
Output:
Array
(
[0] => Donald
)
array_push($arr, $val) This function adds an Code:
element to the end of an $data = array("Donald");

26
array. array_push($data, "Jim");
print_r($data);
?>
Output:
Array
(
[0] => Donald
[1] => Jim
)
array_shift($arr) This function removes an Code:
element from the beginning $data = array("Donald", "Jim", "Tom");
of an array. array_shift($data);
print_r($data);
?>
Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val) This function adds an Code:
element to the beginning of $data = array("Donald", "Jim", "Tom");
an array. array_unshift($data, "Sarah");
print_r($data);
?>
Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
array_reverse($arr) The function reverses the Code:
order of elements in an $data = array(10, 20, 25, 60);
array. print_r(array_reverse($data));
?>
Use this function to re-order Output:
a sorted list of values in Array
reverse for easier (
processing—for example, [0] => 60
when you're trying to begin [1] => 25
with the minimum or [2] => 20
maximum of a set of ordered [3] => 10
values. )
array_merge($arr) This function merges two or Code:
more arrays to create a single $data1 = array("cat", "goat");
composite array. Key $data2 = array("dog", "cow");
collisions are resolved in print_r(array_merge($data1, $data2));

27
favor of the latest entry. ?>
Output:
Use this function when you Array
need to combine data from (
two or more arrays into a [0] => cat
single structure—for [1] => goat
example, records from two [2] => dog
different SQL queries. [3] => cow
)
array_rand($arr) This function selects one or Code:
more random elements from $data = array("white", "black", "red");
an array. echo "Today's color is " .
$data[array_rand($data)];
Use this function when you ?>
need to randomly select from
a collection of discrete Output:
values—for example, Today's color is red
picking a random color from
a list.
array_slice($arr, $offset, This function is useful to Code:
$length) extract a subset of the $data = array("vanilla", "strawberry",
elements of an array, as "mango", "peaches");
another array. Extracting print_r(array_slice($data, 1, 2));
begins from array offset ?>
$offset and continues until
the array slice is $length Output:
elements long. Array
(
Use this function to break a [0] => strawberry
larger array into smaller [1] => mango
ones—for example, when )
segmenting an array by size
("chunking") or type of data.
array_unique($data) This function strips an array Code:
of duplicate values. $data = array(1,1,4,6,7,4);
print_r(array_unique($data));
Use this function when you Output:
need to remove non-unique Array
elements from an array—for ( [0] => 1
example, when creating an [3] => 6
array to hold values for a [4] => 7
table's primary key. [5] => 4 )
array_search($search, $arr) This function searches the Code:
values in an array for a $data = array("blue" => "#0000cc",
match to the search term, "black" => "#000000", "green" =>
and returns the "#00ff00");
corresponding key if found. echo "Found " .
If more than one match array_search("#0000cc", $data);
exists, the key of the first ?>

28
matching value is returned.
Output:
Use this function to scan a Found blue
set of index-value pairs for
matches, and return the
matching index.
each($arr) This function is most often Code:
used to iteratively traverse $data = array("hero" => "Holmes",
$arr is Associate Array an array. Each time each() is "villain" => "Moriarty");
called, it returns the current while (list($key, $value) = each($data))
key-value pair and moves {
the array cursor forward one echo "$key: $value \n";
element. This makes it most }
suitable for use in a loop. Output:
hero: Holmes
villain: Moriarty
array_flip($arr) The function exchanges the Code:
keys and values of a PHP $data = array("a" => "apple", "b" =>
$arr is Associate Array associative array. "ball");
print_r(array_flip($data));
Use this function if you have Output:
a tabular (rows and columns) Array
structure in an array, and you (
want to interchange the rows [apple] => a
and columns. [ball] => b
)
array_values($arr) This function accepts a PHP Code:
array and returns a new array $data = array("hero" => "Holmes",
$arr is Associate Array containing only its values "villain" => "Moriarty");
(not its keys). Its counterpart print_r(array_values($data));
is the array_keys() function. Output:
Array
Use this function to retrieve (
all the values from an [0] => Holmes
associative array. [1] => Moriarty
)

29
UNIT - 2

PHP Built-in Functions


A function is a self-contained block of code that performs a specific task. The function performs
a specific task. The advantages of using functions are:

 Reducing duplication of code


 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding

PHP has a huge collection of internal or built-in functions that you can call directly within your
PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.

PHP User-Defined Functions


In addition to the built-in functions, PHP also allows you to define your own functions. It is a
way to create reusable code packages that perform specific tasks and can be kept and maintained
separately form main program.

Declaring functions
A function is created with the function keyword. simple.php

<?php
function displayVersion() {

echo "this is PHP " . phpversion();


echo "\n";
}

displayVersion();
?>

The function keyword is followed by the function name with round brackets. The body of the
function lies between the curly brackets. We say that we call a function. If we call a function, the
statements inside the function body are executed.

displayVersion(); //This line of the code calls the function.

Output: this is PHP 5.5.9-1ubuntu4.14

Understanding the Variable Scope

However, you can declare the variables anywhere in a PHP script. But, the location of the
declaration determines the extent of a variable's visibility within the PHP program i.e. where the
variable can be used or accessed. This accessibility is known as variable scope.

30
By default, variables declared within a function are local and they cannot be viewed or
manipulated from outside of that function, as demonstrated in the example below:

<?php
function test(){
$greet = "Hello World!";
echo $greet;
}

test(); // Outputs: Hello World!

echo $greet; // Generate undefined variable error


?>

Returning values from a function The return keyword is used to return a value from the
function. A function may or may not return a value.

returning.php
<?php
function maximum($x, $y) {

if ($x > $y) {

return $x;
} else {

return $y;
}
}

$a = 23;
$b = 32;

$val = maximum($a, $b);


echo "The max of $a and $b is $val \n";
?>

We have a maximum() function. It returns a max for two numbers. We could not name it max,
because there is already a built-in max() function.

If the $x variable is greater than $y, we return $x. Otherwise we return $y.

$val = maximum($a, $b);

The value returned by the maximum() function is assigned to the $val variable.

echo "The max of $a and $b is $val \n";

We print the max value of the two numbers in the browser.

31
Passing Arguments to functions Most functions accept arguments. Arguments are values
that are sent to the function. The functions process the values and possibly return some outcome.

<?php

function FTC($c) {

return $c * 9/5 + 32;


}

echo FTC(100);
echo "\n";
echo FTC(0);
echo "\n";
echo FTC(30);
echo "\n";

?>
In our example (fahrenheit.php), we convert Fahrenheit temperature to Celsius. The FTC()
function accepts one argument $c, which is the Celsius temperature.

http://localhost/php/fahrenheit.php
212
32
86

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

<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
?>

PHP function recursion


Recursion, in mathematics and computer science, is a method of defining functions in which the
function being defined is applied within its own definition. In other words, a recursive function
calls itself to do its job. Recursion is an alternative to iteration. Recursion is the main approach in
functional languages. A typical example is the calculation of the factorial.

recursion.php
<?php

32
function factorial($n) {
if ($n==0) {
return 1;
} else {
return $n * factorial($n - 1);
}
}

echo factorial(4), "\n";


?>

Dynamic Function Calls


Also called Variable Functions. This means that if a variable name has parentheses appended to
it, PHP will look for a function with the same name as whatever the variable evaluates to, and
will attempt to execute it. Among other things, this can be used to implement callbacks, function
tables, and so forth.

Variable functions won't work with language constructs such as echo, print, unset(), isset(),
empty(), include, require and the like.

<?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>

This will display following result −

Hello

Variable Functions with Parameters


<?php
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}

$function = 'bar';
$function('test'); // This calls bar()
?>

33
PHP Predefined functions
Predefined or built in functions are those functions which comes with PHP by default. But to
make some of these functions to work, one need to have some PHP extensions compiled into
PHP. Otherwise it will give some fatal errors. For example to use MySql functions to work
properly, PHP should be compiled with Mysql support.

It's important to know what a function returns, or if a function works directly on a passed in
value etc., to improve the quality of the PHP code.

1. func_get_args — Returns an array comprising a function's argument list

function foo() {
// returns an array of all passed arguments
$args = func_get_args();

foreach ($args as $k => $v) {


echo "arg".($k+1).": $v\n";
}
}
foo(); /* prints nothing */

foo('hello'); /* prints arg1: hello */

foo('helo', 'world', 'again');/* prints arg1: helo arg2: world arg3:again*/

2. function_exists — Return TRUE if the given function has been defined

bool function_exists ( string $function_name )

<?php
if (function_exists('imap_open')) {
echo "IMAP functions are available.<br />\n";
} else {
echo "IMAP functions are not available.<br />\n";
}
?>
PHP Mailing Functions
The mail() function allows you to send emails directly from a script.

Syntax: mail(to,subject,message,headers,parameters);

Parameter Description

34
to Required. Specifies the receiver / receivers of the email
subject Required. Specifies the subject of the email. Note: This parameter cannot
contain any newline characters
message Required. Defines the message to be sent. Each line should be separated with
a LF (\n). Lines should not exceed 70 characters.

Windows note: If a full stop is found on the beginning of a line in the


message, it might be removed. To solve this problem, replace the full stop
with a double dot:
<?php
$txt = str_replace("\n.", "\n..", $txt);
?>
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n).

Note: When sending an email, it must contain a From header. This can be set
with this parameter or in the php.ini file.
parameters Optional. Specifies an additional parameter to the sendmail program (the one
defined in the sendmail_path configuration setting). (i.e. this can be used to
set the envelope sender address when using sendmail with the -f sendmail
option)

<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters


$msg = wordwrap($msg,70);

// send email
mail("someone@example.com","My subject",$msg);
?>

<?php // Always set content-type when sending HTML email


$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

mail($to,$subject,$message,$headers);
?>

35
PHP INCLUSIVE FUNCTIONS

You can include the content of a PHP file into another PHP file before the server executes it.
There are two PHP functions which can be used to include one PHP file into another PHP file.
 include() Function
 require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that
can be reused on multiple pages. This will help developers to make it easy to change the layout
of complete website with minimal effort. If there is any change required then instead of changing
thousand of files just change included file.

The PHP include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the include() function generates a
warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with
the following content.
<a href="http://www.abc.com/index.htm">Home</a> -
<a href="http://www.abc.com/ebxml">ebXML</a> -
<a href="http://www.abc.com/about">ABOUT</a> -
<a href="http://www.abc.com/contact">ContactUS</a> <br />

Now create as many pages as you like and include this file to create header. For example now
your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p> ?>
</body>
</html>
It will produce the following result – (displays hyperlinks and text printed)

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the
include function. If there is any problem in loading a file then the require() function generates a
fatal error and halt the execution of the script.

PHP include vs. require

There is no much difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not
continue executing if files are missing or misnamed.

36
You can try using above example with require() function and it will generate same result. But if
you will try following two examples where file does not exist then you will get different results.
Note: Rename the “menu.php” as “xxmenu.php” in the above example program and try it with both
include() and require() functions

<?php
include("xxmenu.php");
?>
This will produce the following result −
Output: This is an example to show how to include wrong PHP file!

Now lets try same example with function.

<?php
require("xxmenu.php");
?>

Output: This time file execution halts and nothing is displayed.


NOTE − You may get plain warning messages or fatal error messages or nothing at all. This
depends on your PHP Server configuration.

require_once() statement can be used to include a php file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with require_once() statement, and does not find b.php,
a.php stops executes causing a fatal error.

Syntax: require_once('name of the calling file with path');

“x.php” contents
<?php
echo "today is:".date("Y-m-d");
?>

The above file x.php, is included twice with require_once() statement in the following file y.php.
But from the output you will get that the second instance of inclusion is ignored, since
require_once() statement ignores all the similar inclusions after the first one.

“y.php”
<?php
require_once('x.php');

37
require_once('x.php');
?>

If a calling script does not find a called script with the require_once statement, it halts the
execution of the calling script.

PHP include_once()

The include_once() statement can be used to include a php file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with include_once() statement, and does not find b.php,
a.php executes with a warning, excluding the part of the code written within b.php.

Syntax: include_once('name of the called file with path');


Explain same x.php and y.php example as above

If a calling script does not find a called script with the include_once statement, it halts the
execution of the calling script.

Recursive inclusion of files can be avoided using require_once() OR include_once()

Object-Oriented Programming Concepts in PHP


PHP is a server-side scripting language, mainly used for web development but also used as a
general-purpose programming language. Object-Oriented Programming (PHP OOP), is a type of
programming language principle added to php5, that helps in building complex, reusable web
applications.

The Object Oriented concepts in PHP are:

 Class
 Objects
 Inheritance
 Interface
 Abstraction
 Magic Methods

Class & Object:

 Class is a programmer-defined data type, which includes local methods and local variables.
 Class is a collection of objects. Object has properties and behaviour.
 First we have to define a php class, where classname should be same as filename.

38
<?php
class Books{
public function name(){
echo “Drupal book”;
}
public function price(){
echo “900 Rs/-”;
}
}
To create php object we have to use a new operator. Here php object is the object of the Books Class.
$obj = new Books();
$obj->name();
$obj->price();
?>

Output:
Drupal book
900 Rs/-

Constructor
void __construct ( [mixed args [, ...]] )

PHP 5 allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In
order to run a parent constructor, a call to parent::__construct() within the child constructor is
required.

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it
will search for the old-style constructor function, by the name of the class. Effectively, it means
that the only case that would have compatibility issues is if the class had a method named
__construct() which was used for different semantics.

<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}

39
$obj = new BaseClass();
$obj = new SubClass();
?>
Destructor
void __destruct ( void )

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as
C++. The destructor method will be called as soon as all references to a particular object are
removed or when the object is explicitly destroyed. Like constructors, parent destructors will not be
called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call
parent::__destruct() in the destructor body.

Note: Destructor is called during the script shutdown so headers are always already sent.

Note: Attempting to throw an exception from a destructor causes a fatal error.

The Destructor method will be called as soon as there are no other references to a particular
object, or in any order during the shutdown sequence. Destructor automatically call at last.

<?php
class demo
{
function __construct()
{
echo "object is initializing their propertie"."<br/>";
}
function work()
{
echo "Now works is going "."<br/>";
}

function __destruct()
{
echo "after completion the work, object destroyed automatically";
}
}
$obj= new demo();

$obj->work();
//to check object is destroyed or not
echo is_object($obj);
?>
Output
object is initializing their properties
Now works is going
1
after completion the work, object destroyed automatically

40
Access Control Modifiers / Visibility
PHP access modifiers are used to set access rights with PHP classes and their members that are the
functions and variables defined within the class scope. In PHP, there are some keywords representing
these access modifiers. These keywords will be added with PHP classes and its members.

Now, let us have a look at the following list to know about the possible PHP keywords used as
access modifiers.

1. public – class or its members defined with this access modifier will be publicly accessible
from anywhere, even from outside the scope of the class.
2. private – class members with this keyword will be accessed within the class itself. It
protects members from outside class access with the reference of the class instance.
3. protected – same as private, except by allowing subclasses to access protected superclass
members.
4. abstract – This keyword can be used only for PHP classes and its functions. For
containing abstract functions, a PHP class should be an abstract class.
5. final – It prevents subclasses to override super class members defined with final keyword.

Scope Resolution Operator (::)


The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the
double colon, is a token that allows access to static, constant, and overridden members or
methods of a class.

When referencing these items from outside the class definition, use the name of the class.

Eg.: MyClass::CONST_VALUE;

Note: Two special keywords self and parent are used to access members or methods from inside
the class definition. Eg: parent::CONST_VALUE . "\n";
self::$my_static . "\n";

Static Keyword

Declaring class members or methods as static makes them accessible without needing an
instantiation of the class. A member declared as static cannot be accessed with an instantiated
class object (though a static method can).

The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no
visibility declaration is used, then the member or method will be treated as if it was declared as
public.

Because static methods are callable without an instance of the object created, the pseudo variable
$this is not available inside the method declared as static.
41
In fact static method calls are resolved at compile time. When using an explicit class name the
method is already identified completely and no inheritance rules apply. If the call is done by self
then self is translated to the current class, that is the class the code belongs to. Here also no
inheritance rules apply.

Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Comparison of Static and Constant


Static
1. Can has a access modifier.
Eg: private static $private_static = "can access only inside the class";
2. Depending the visibility you can access static variables.
//inside the class
self::$variable_name;
static::$variable_name;
//outside the class
class_name::$variable_name;
3. Can change the value after declaration.
self::$variable_name = "New Value";
static::$variable_name = "New Value";
4. No need to initialize when declare.
public static $variable_name;
5. Normal variable declaration rules applied(ex: begins with $)
6. Can create inside a function.
class A{
function my_function(){
static $val = 12;
echo ++$val; //13
}
}

Constant
1. Always public cannot put access modifiers.
class A{
const my_constant = "constant value";
public const wrong_constant="wrong" // produce a parse error
}

2. Anywhere you can access constant.


//inside the class
self::variable_name;
static::variable_name;
//outside the class
class_name::variable_name;

42
3. Cannot change the value after declaration.
self::variable_name = "cannot change"; //produce a parse error

4. Must initialize when declare.


class A{
const my_constant = "constant value";// Fine
const wrong_constant;// produce a parse error
}

5. Must not use $ in the beginning of the variable(Other variable rules applied).
class A{
const my_constant = "constant value";// Fine
const $wrong_constant="wrong";// produce a parse error
}

6. Cannot declare inside a function.

Creating Objects in PHP


When class is created, we can create any number of objects to that class. The object is created
with the help of new keyword.

Calling Member Function


When the object is created we can access the variables and method function of the class with the
help of operator ‘->, accessing the method is done to get the information of that method. Also
look into how we can access object properties via variables
<?php
class Mobile {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setName($par){
$this->title = $par;
}
function getName(){
echo $this->title ." <br/>";
}
}
$Samsung = new Mobile();
$Samsung->setName( "SamsungS8 );
$Samsung->setPrice( 90000 );
Now you call another member functions to get the values set by in above example
$Samsung->getName();

43
$Samsung->getPrice();
?>
Output :
Samsung S8
90000

Inheritance
When the properties and the methods of the parent class are accessed by the child class, we call
the concept has inheritance. The child class can inherit the parent method and give own method
implementation, this property is called overridden method. When the same method of the parent
class is inherited we call as inherited method. Now let us see types of inheritance supported in
Object Oriented Programming and corresponding Php inheritance examples.

Types Of Inheritance

1. Single Level Inheritance


2. Multilevel Inheritance

Single Level Inheritance: In Single Level Inheritance the Parent class methods will be
extended by the child class. All the methods can be inherited.

<?php
class A {
public function printItem($string) {
echo ' Hi : ' . $string;
}
public function printPHP() {
echo 'I am from valuebound' . PHP_EOL;
}
}
class B extends A {
public function printItem($string) {
echo 'Hi: ' . $string . PHP_EOL;
}
public function printPHP() {
echo "I am from ABC";
}
}
$a = new A();
$b = new B();

44
$a->printItem('Raju');
$a->printPHP();
$b->printItem('savan');
$b->printPHP();
?>

Output
Hi : Raju
I am from valuebound
Hi: savan
I am from ABC

MultiLevel Inheritance : In MultiLevel Inheritance, the parent class method will be inherited
by child class and again subclass will inherit the child class method.

<?php
class A {
public function myage() {
return ' age is 80';
}
}
class B extends A {
public function mysonage() {
return ' age is 50';
}
}
class C extends B {
public function mygrandsonage() {
return 'age is 20';
}
public function myHistory() {
echo "Class A " .$this->myage();
echo "Class B ".$this-> mysonage();
echo "Class C " . $this->mygrandsonage();
}
}
$obj = new C();

45
$obj->myHistory();
?>

Output
Class A is 80
Class B is 50
Class C 20

INTERFACES:

 An interface is a description of the actions that an object can do.


 Interface is written in the same way as the class the declaration with interface keyword.
Rules of Interfaces:
 All methods declared in an interface must be public; this is the nature of an interface.
 All methods in the interface must be implemented within a class; failure to do so will result in a
fatal error.
 The class implementing the interface must use the exact same method signatures as are defined in
the interface
 Interfaces can be extended like classes using extends operator.
<?php
interface A {
public function setProperty($x);
public function description();
}
class Mangoes implements A {
public function setProperty($x) {
$this->x = $x;
}
public function description() {
echo 'Describing' . $this->x . tree;
}
}
$Mango = new Mangoes();
$Mango->setProperty(mango);
$Mango->description();
?>
Output:
Describing Mango tree
2) Interface can be extended with another interface using extends keyword
<?php
interface A {
public function Compute();
}
interface B extends A {
public function Divide();
}
class C implements B {
public function Divide() {
$var=10;

46
$var1=2;
$var3=$var/$var1;
echo “division of 10/2 is” . $var3;
}
public function Compute() {
$a=2;
$b=3;
$c=$a*$b;
echo “multiplication of 2*3 is” . $c;
}
}
$obj = new C();
$obj->Divide();
$obj->Compute();
?>
Output:
division of 10/2 is 5
multiplication of 2*3 is 6
Note on Interfaces:-
 We cannot create objects to interface, but the class implementing interface can have objects
 We cannot define a variable in an interface.
 If we extend interface all the methods of the interface must be implemented in the child class.

Abstract Classes:
 An abstract class is a class that contains at least one abstract method. The abstract method is
function declaration without anybody and it has the only name of the method and its parameters.
 There can be any number of methods in the class and we have to declare the class as abstract only
when there is an abstract method
<?php
abstract class Cars {
public abstract function getCompanyName();
public abstract function getPrice();
}
class Baleno extends Cars {
public function getCompanyName() {
return "Maruthi Suzuki" . '<br/>';
}
public function getPrice() {
return 720000 . '<br/>';
}
}

class Santro extends Cars {


public function getCompanyName() {
return "Hyundai" . '<br/>';
}
public function getPrice() {
return 300000 . '<br/>';
}
}

47
$car = new Baleno();
$car1 = new Santro();
echo $car->getCompanyName();
echo $car->getPrice();
echo $car1->getCompanyName();
echo $car1->getPrice();
?>
Output for the above code is:
Maruthi Suzuki
720000
Hyundai
300000

Notes on Abstract classes:


 Objects cannot be created for the abstract classes.
 If a class has only one method as abstract, then that class must be an abstract class.
 The child class which extends an abstract class must define all the methods of the abstract class.
 If the abstract method is defined as protected in the parent class, the function implementation
must be defined as either protected or public, but not private.
 The signatures of the methods must match, optional parameter given in the child class will not be
accepted and error will be shown.
 Abstract classes that declare all their methods as abstract are not interfaces with different names.
One can implement multiple interfaces, but not extend multiple classes (or abstract classes).
Now Let us see the difference between abstract class and interface.

Abstract class Interface

It can have constants, members, method stubs It can only have constants and methods stubs.
(methods without a body), methods
Methods of interface should only be public not any other
Methods and members can have public or
visibility
protected visibility
An interface can extend or a class can implement multiple other
The concept of multiple inheritances not
interfaces.
supported.
No need of implementing methods from parent interface when
Child class must implement all the abstract method
interface is extending another interface
of parent class when extend keyword is used.

Magic Methods
In PHP, we can define some special functions that will be called automatically. Such functions
require no function call to execute the code inside these functions. With this special feature, they
can be referred as magic functions or magic methods. For using these magic methods in PHP, we
need to be known about the following list of points.

48
 PHP magic methods names are limited to some list of PHP supported keywords, like
construct, destruct and etc.
 And, these names are reserved. So, we should not define any function with the name of
PHP magic methods.
 PHP magic methods should be started with (__) symbol.
 For defining the magic method with (__) followed by a different name, apart from the list
of PHP supported naming keyword, we need to simulate PHP magic functionality.
 These special functions should be defined by the user. But no need to call them explicitly.
Rather, it will be called on appropriate event occurrence. For example, class
__construct() will be called while instantiating the class.
 PHP magic methods must be defined inside the class.

Magic Methods Invoked on Creating Class Instance


 __construct()/__destruct() – We have seen enough about these two magic methods while
discussing constructors and destructors which is one of the object oriented feature
supported in PHP.
Magic Methods with PHP Overloading
The following list of PHP magic methods is used to deal with inaccessible class members created
at run time by using PHP overloading concept.
 __get()/__set() – These are magic getters and setters for getting and putting values for
class properties created dynamically by PHP property overloading.
 __isset() – This magic method will be invoked automatically while checking whether a
required overloaded property is set or not, by using the PHP isset() function.
 __unset() – Similarly, when we call PHP unset() function on such dynamically created
properties, this magic method will automatically be invoked.
 __call()/__callStatic() – These two magic methods are dedicated for accessing
dynamically created but invisible methods on PHP method overloading. These differ,
where __call() will invoke normal PHP overloaded methods, and __callStatic() will
invoke static methods.
Other few Magic Methods in PHP
 __toString() – This method is expected return a string value while using class instances
with PHP printing statements.
 __clone()-This function is used while PHP Object Cloning.

Overloading
Overloading in PHP provides means to dynamically "create" properties and methods. ... In
PHP, overloading means you can add object members at run-time, by implementing some of
the magic methods like __set , __get , __call etc.

//Method Overloading

class test
{
public function __call($method_name , $parameter)

49
{//Func overloading logic for func name overlodedFunction
if($method_name == "overlodedFunction") {
$count = count($parameter);
switch($count)
{
case "1": //Business log in case of overlodedFunction function has 1 argument
echo "You are passing 1 argument"; break;
case "2": //Incase of 2 parameter
echo "You are passing 2 parameter"; break;
default: throw new exception("Bad argument");
}
}
else{ throw new exception("Function $method_name does not exists "); }
}
}
$a = new test();
$a->overlodedFunction("ankur");
$a->overlodedFunction("techflirt" , "ankur");

//Member Overloading
class PropertyTest
{
private $data = array(); /** Location for overloaded data. */
public $declared = 1; /** Overloading not used on declared properties. */
private $hidden = 2; /** Overloading only used on this when accessed outside the class. */
public function __set($name, $value)
{
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name)
{
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) { return $this->data[$name]; }
}
}
$obj = new PropertyTest;
$obj->a = 1; echo $obj->a . "\n\n";

50
OUTPUT:
Setting 'a' to '1' Getting 'a' 1

Overriding in PHP

Implementation of overriding in php is very easy. Overriding is process of modifying the


inherited method. So, if your parent class has a function, you can create function with same name
in your child class to override the function. Implementation of overriding cannot be achieved by
creating 2 functions with same name and different argument in php, because we cannot create
same name function more than 1 time in php class. Following is example of overriding of
method in php.

class testParent
{
public function f1()
{
echo 1;
}
public function f2()
{
echo 2;
}
}
class testChild
{
function f2($a) //overriding function f2
{
echo "$a";
}
}
$a = new testChild();
$a->f2("ankur");//it will print ankur

Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items,
with, for example a foreach statement. By default, all visible properties will be used for the
iteration.

The foreach iterates through all visible variables (public variables) that can be accessed. To take
it a step further you can implement one of PHP 5's internal interface named Iterator. This allows
the object to decide what and how the object will be iterated.

<?php
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';

51
public $var3 = 'value 3';

protected $protected = 'protected var';


private $private = 'private var';

function iterateVisible() {
echo "MyClass::iterateVisible:\n";
foreach ($this as $key => $value) {
print "$key => $value\n";
}
}
}

$class = new MyClass();

foreach($class as $key => $value) {


print "$key => $value\n";
}
echo "\n";

$class->iterateVisible();

?>

The above example will output:

var1 => value 1


var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var
Object Cloning
Object cloning is creating a copy of an object. An object copy is created by using the clone
keyword and the __clone() method cannot be called directly. In PHP, cloning an object is doing a
shallow copy and not a deep copy. Meaning, the contained objects of the copied objects are not
copied. If you wish for a deep copy, then you need to define the __clone() method.
When there is a need that you do not want the outer enclosing object to modify the internal state
of the object then the default PHP cloning can be used.

52
Copy Objects by Assignment

In the below code, I am attempting to copy an object by using the assignment operator. So what
happens is, the instance is just a pointer to the old instance. We can verify that by updating the
values of its properties. When the values of the new instance are updated it gets reflected in the
old instance. So, this type of copy is just a duplicate reference to the original instance.
Technically this is not a copy, but it is just assigning the object’s reference to another object.

<?php The output is,


class Animals
{ Animals Object
public $name; (
public $category; [name] => Cat
} [category] => Pet Animal
$objAnimals = new Animals(); )
//setting properties Values of Copied object $objCopied:
Animals Object
$objAnimals->name = "Lion";
(
$objAnimals->category = "Wild Animal"; [name] => Cat
//Copying object [category] => Pet Animal
$objCopied = $objAnimals; )
$objCopied->name = "Cat";
$objCopied->category = "Pet Animal"
print_r($objAnimals);
print_r($objCopied);
?>

Object Copy by clone


In the below example, we are copying objects by using PHP clone keyword. PHP’s clone method
does a shallow copy and so, any changes made in the cloned object will not affect original
object. __clone is a magic method in PHP. Magic methods are predefined in PHP and starts with
“__” (double underscore). They are executed in response to some events in PHP.

<?php output of this code.


//Creating instance of Animals class
$objAnimals = new Animals(); Animals Object
//Assigning values (
$objAnimals->name = "Lion"; [name] => Lion
$objAnimals->category = "Wild Animal"; [category] => Wild Animal
//Cloning the original object )
$objCloned = clone $objAnimals; Values of Cloned object $objCopied:
Animals Object
$objCloned->name = "Elephant";
(
$objCloned->category = "Wild Animal"; [name] => Elephant
print_r($objAnimals); [category] => Wild Animal
print_r($objCloned); )
?>

53
Comparing objects in PHP

Like comparing variables PHP objects are also compared with one another. There are two types
of operators that are used to compare objects.
 Comparision operator (==)
 Identity operator (===)
Comparison operator ( == ) compares two objects if both have same properties. And Identity
operator ( === ) compares two objects variables if they actually point the same object.
<?php

$p1 = new Point(10,20);

$p2 = $p1; // $p1 and $p2 objects are identical when we use identity operator ( ===) to compare
because they are all refer to the same object.

$p3 = new Point(10,20); //$p3 object is not identical to the $p1 when we use identity operator (
===) to compare even their properties values are the equal.
?>
Design Patterns
Design Patterns aren’t analysis patterns, they are not descriptions of common structures
like linked lists, nor are they particular application or framework designs. In fact, design patterns
are “descriptions of communicating objects and classes that are customized to solve a general
design problem in a particular context.” In other words, Design patterns provide a generic
reusable solution to the programming problems that we encounter every day. Design patterns are
not ready classes or libraries, that can be simply applied to your system, this is not a concrete
solution that can be converted in to source code, design patterns are much more than that. They
are patterns, or templates, that can be implemented to solve a problem in different particular
situations.
Design patterns help to speed up the development, as the templates are proven and from
the developer’s position, only implementation is required. Design patterns not only make
software development faster, but also encapsulate big ideas in a simpler way. Also, be careful not
to use them in wrong places in order to avoid unpleasant situations.

Singleton

This is one of the most popular patterns. When developing web applications, it often makes
sense conceptually and architecturally to allow access to only one instance of a particular class
(during runtime).

Strategy

The strategy pattern is based on algorithms. You encapsulate specific families of algorithms
allowing the client class responsible for instantiating a particular algorithm to have no
knowledge of the actual implementation. (using Interfaces instead of class)

54
Model-View-Controller

The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break
up code into logical objects that serve very specific purposes. Models serve as a data access layer
where data is fetched and returned in formats usable throughout your application. Controllers
handle the request, process the data returned from models and load views to send in the response.
And views are display templates (markup, xml, etc) that are sent in the response to the web
browser.

MVC is the most common architectural pattern used in the popular PHP frameworks.

FINAL keyword

Final Keyword is applicable to only class and class methods. We cannot declare variables as
Final in PHP.

So if you declare class method as a Final then that method cannot be override by the child class.
Same as method if we declare class as a Final then that class cannot be extended any more.

Declaring Class as Final Declaring Method as Final


// This class cannot be Extended class parent_class
final class parent_class {
{ // We Can not override this method
public function class_method() // As it declared as final
{ final public function class_method()
/* Code Here */ {
} /* Code Here */
} }
}
class child_class extends parent_class
{ class child_class extends parent_class
public function class_method() {
{ public function class_method()
/* Code Here */ {
} /* Code Here */
} }
}

Reflection

PHP 5 introduced very useful Reflection API which is not much known to developers so Today
we will take a brief overview of Reflection API in PHP. Reflection is the built-in class of PHP
which allows us to retrieve all the information about classes, class properties, functions,
methods, and exceptions. PHP supports reflection using the Reflection API in PHP5. Reflection

55
is not needed for a vast majority of projects. Reflection API is very useful in cases you are
developing the complex application.
Reflection is kind of observer which observes the script. Reflection is mainly useful for
dynamically invoking methods that a class has and contains a number of different methods to
obtain information about the structure of the class.

What is Reflection API?


Reflection API is an object-oriented extension of PHP. Reflection API provides a much larger
classes and methods for solving problems of reflection. Reflection is very easy to use in your
code. Reflection is useful when you are using OOP concept for your development as it works
more effectively with object-oriented PHP.

Reflection API is only used for retrieving information about the classes. You can use
ReflectionFunction class to get information about a given function; ReflectionClass provides
information of the object directly when executing the script.

<?php
class myparent {
public function foo($bar) {
// do stuff
}
}

class mychild extends myparent {


public $val;
private function bar(myparent &$baz) {
// do stuff
}
public function __construct($val) {
$this->val = $val;
}
}
$reflect = new ReflectionClass('mychild');
echo $reflect;
?>
Note: http://localhost/ reflection.php
Execute the URL and view source code for getting Documentation.

Type Hinting

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting
with int and string isn't supported. In simple word to remember, type hinting means providing
hints to function to only accept the given data type. In technical word we can say that
Type Hinting is method by which we can force function to accept the desired data type. In PHP
we can use type hinting for Object, Array and callable data type only.

56
<?php
class Test1{
public $var = 'this is test';
}
function typehint(Test1 $t1){
echo $t1->var;
}
typehint(new Test1()); // Will print this is test
?>

File handling is needed for any application. For some tasks to be done file needs to be processed.
File handling in PHP is similar as file handling is done by using any programming language like
C. PHP has many functions to work with normal files.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer. (the readfile() function
returns the number of bytes read on success), useful if all you want to do is open up a file and
read its contents.

File Opening Modes


Before we look how to open a file in PHP you need to know that a file can be opened in different
modes. For example you can open a file in read only mode or in read and write modes. Take a
look at the table below for the different modes:

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it
doesn’t exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it
doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
To open a file PHP you can use the fopen() function. This function takes two parameters, where
the first parameter contains the name of the file and the second parameter is the modes that
should be used to open the file.

Closing a File
After you have opened a file and you are done (for instance reading its contents) then you should
close the file. A fopen() function should always match with a fclose() function. Take a look at an
example:

<?php
$file = fopen("test.txt","w");
fclose($file);
?>

57
Reading a File Line by Line
The fgets() function is used to read a single line from a file. After the line has been read the file
pointer is pointing to the next line in the file. This is very useful, because we could now read the
file line by line.

Reading a File Character by Character

The function fgetc() can be used to read a character from a file. We now can use the previous
example to read a file character by character. Take a look at the following example:

<?php
$file = fopen("test.txt", "r") or exit("Unable to open the file!");
while(!feof($file))
{
//echo fgets($file). "<br />"; // used to grab one line and echo this line onto the screen
echo fgetc($file). "<br />"; //Used to grab character by character
}
fclose($file);
?>

PHP Check End-Of-File - feof()


The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is
useful for looping through data of unknown length.

PHP Write to File - fwrite() used to write to a file.


The first parameter of fwrite() contains the name of the file to write to and the second parameter
is the string to be written. Note: If you are having errors when trying to get this code to run,
check that you have granted your PHP file access to write information to the hard drive.

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Delete a File
$my_file = 'file.txt';
unlink($my_file);

58
PHP file_get_contents() Function
The file_get_contents() reads a file into a string.
This function is the preferred way to read the contents of a file into a string. Because it will use
memory mapping techniques, if this is supported by the server, to enhance performance.
Syntax
file_get_contents(path,include_path,context,start,max_length)

Parameter Description
path Required. Specifies the file to read
include_path Optional. Set this parameter to '1' if you want to search for the file in the
include_path (in php.ini) as well
context Optional. Specifies the context of the file handle. Context is a set of options
that can modify the behavior of a stream. Can be skipped by using NULL.
start Optional. Specifies where in the file to start reading. This parameter was
added in PHP 5.1
max_length Optional. Specifies how many bytes to read. This parameter was added in
PHP 5.1

Note: file_get_contents() — Reads entire file into a string. This is the preferred way to read the
contents of a file into a string. It will use memory mapping techniques if supported by your OS
to enhance performance.
PHP fgetcsv() Function
The fgetcsv() function parses a line from an open file, checking for CSV fields.
The fgetcsv() function stops returning on a new line, at the specified length, or at EOF,
whichever comes first. This function returns the CSV fields in an array on success, or FALSE on
failure and EOF.
Syntax fgetcsv(file,length,separator,enclosure)

Few other PHP 5 File system Functions


Function Description Syntax
basename() Returns the filename component of string basename ( string $path
a path [, string $suffix ] )
chmod() Changes the file mode bool chmod ( string $filename , int $mode
)
copy() Copies a file bool copy (string $source , string $dest
[, resource $context ] )
dirname() Returns the directory name string dirname ( string $path [, int
component of a path $levels = 1 ] )

file_exists() Checks whether or not a file or bool file_exists ( string $filename )


directory exists
filesize() Returns the file size int filesize ( string $filename )
pathinfo() Returns information about a file mixed pathinfo ( string $path [, int

59
path $options = PATHINFO_DIRNAME |
PATHINFO_BASENAME |
PATHINFO_EXTENSION |
PATHINFO_FILENAME ] )
fileperms () Returns the permissions of a file int fileperms ( string $filename )

realpath() Returns the absolute pathname string realpath ( string $path )


unlink() Deletes a file bool unlink ( string $filename [, resource
$context ] )
flock() Portable advisory file locking bool flock ( resource $handle , int
$operation [, int &$wouldblock ] )

Directory Functions
1) The mkdir() function creates a directory. This function returns TRUE on success, or FALSE
on failure.
Syntax: mkdir(path,mode,recursive,context)

Parameter Description
path Required. Specifies the name of the directory to create
mode Optional. Specifies permissions. By default, the mode is 0777 (widest
possible access).

The mode parameter consists of four numbers:

 The first number is always zero


 The second number specifies permissions for the owner
 The third number specifies permissions for the owner's user group
 The fourth number specifies permissions for everybody else
Possible values (to set multiple permissions, add up the following numbers):
 1 = execute permissions
 2 = write permissions
 4 = read permissions
recursive Optional. Specifies if the recursive mode is set (added in PHP 5)
context Optional. Specifies the context of the file handle. Context is a set of options
that can modify the behavior of a stream (added in PHP 5)

2) rmdir — Removes directory

Syntax: bool rmdir ( string $dirname [, resource $context ] )


Attempts to remove the directory named by dirname. The directory must be empty, and the
relevant permissions must permit this. A E_WARNING level error will be generated on failure.

3) scandir — List files and directories inside the specified path

60
Syntax: array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [,
resource $context ]] ) //Returns an array of files and directories from the directory.

4) readdir() function returns the name of the next entry in a directory.

Syntax: readdir(dir_handle); //Returns the entry name (filename) on success. FALSE on


failure

5) The is_dir() function checks whether the specified file is a directory.

Syntax is_dir(file) //returns TRUE if the directory exists.

<?php
if(!is_dir("testing"))
mkdir("testing","777");

if(fileperms ("C:/xampp/htdocs/myPHP/testing/") !== 777) { //Check directory permissions


if(chmod("C:/xampp/htdocs/myPHP/testing/", 777)) //change its mode
print("Given Access to open folder");
else
print("Unable to change mode");
}

$fp = fopen"C:/xampp/htdocs/myPHP/testing/testing.php", 'w'); //Open OR Create file


fwrite($fp,"testing"); //Write Content
$files = scandir($dir); //Returns list of directory contents as array
print_r($files);

/*if(is_dir("testing")) {
rmdir("testing"); }*/
?>

61
PHP strings
A string is a collection of characters. String is one of the data types supported by PHP.The string
variables can contain alphanumeric characters.

The simplest way to create a string is to use single quotes.

<?php
echo ‘I \'ll be back after 20 minutes’;
?>
The double quotes are used to create relatively complex strings compared to single quotes.
Variable names can be used inside double quotes and their values will be displayed.
<?php
$name='Alicia';
echo "$name is friends with kalinda";
?>

PHP string functions

PHP string functions are used to manipulate string values.

Function Description Example Output


strtolower Used to convert all string characters echo strtolower( outputs benjamin
to lower case letters 'Benjamin');
strtoupper Used to convert all string characters echo strtoupper('george w outputs GEORGE W
to upper case letters bush'); BUSH
strlen The string length function is used to echo strlen('united states of 24
count the number of character in a america');
string. Spaces in between characters
are also counted
explode Used to convert strings into an array $settings = explode(';', Array ( [0] =>
variable "host=localhost; db=sales; host=localhost [1] =>
uid=root; pwd=demo"); db=sales [2] =>
print_r($settings); uid=root [3] =>
pwd=demo )
implode Used to convert array into a string $arr = array('Hello', Hello World
variable 'World!', Beautiful Day!
'Beautiful',
'Day!');
echo implode(" ",$arr);
substr Used to return part of the string. It $my_var = 'This is a really This is a re...

62
Function Description Example Output
accepts three (3) basic parameters. long sentence that I wish to
The first one is the string to be cut short';echo
shortened, the second parameter is substr($my_var,0, 12).'...';
the position of the starting point, and
the third parameter is the number of
characters to be returned.
str_replace Used to locate and replace specified echo str_replace ('the', that laptop is very
string values in a given string. The 'that', 'the laptop is very expensive
function accepts three arguments. expensive');
The first argument is the text to be
replaced, the second argument is the
replacement text and the third
argument is the text that is analyzed.
strpos Used to locate the and return the echo strpos('PHP 4
position of a character(s) within a Programing','Pro');
string. This function accepts two
arguments
str_word_count Used to count the number of words echo str_word_count ('This 12
in a string. is a really long sentence
that I wish to cut short');
ucfirst Make the first character of a string echo ucfirst('respect'); Outputs Respect
value upper case
lcfirst Make the first character of a string echo lcfirst('RESPECT'); Outputs rESPECT
value lower case

Splitting and joining PHP variables and strings


Sometimes you want to split a variable into parts. Remember how FOREACH goes through an
array line by line. Imagine that this information had been read from a text file:

Imagine that this data is in an array:


$stocklist[0]="oranges, 50p, Spain";
$stocklist[1]="bananas, 40p, Windward Island";
$stocklist[2]="apples, 30p, UK";

This loop might output the contents to a page:


foreach ($stocklist as $item) {
echo "<p>$item</p>";
}
To use data properly though you would need to split it up into parts. Each line is made up of:
 fruit name
 price

63
 country of origin

You can split those three things up because they are separated by commas. There are a number of
built in PHP functions which do this job but explode() is probably best. It will take a string and
split it every time there is a special character (e.g. a comma). This code goes through the array
bit by bit and explodes each bit: $items = explode(',', $item);

The string is split into an array. Paste that into arraysandloops.php and you should see three
arrays printed each with a stock item name, price and country in it. One array is printed each
time through the loop.
Extra spaces and TRIM
When splitting text you may find you end up with extra blank spaces at the beginning and end of
the data. The problem is that if you then use the data in conditional statements (e.g. IFs) you may
not get matches because of the extra spaces. TRIM removes any extra blank spaces (including
invisible carriage returns and tabs):
$string=" a string with spaces at beginning and end ";
$string=trim($string);

Joining strings
You can also join strings together. To join the strings held in two variables:
$both=$first.$second;

To join a variable and a literal:


$both=$first."a piece of text in quotes is known as a string literal for reasons which do not matter.";
Or
$both="This $stockitemname is worth \$40 to which you might say \"Wow, cheap\".";
Now the slashes tell PHP which characters are part of the string.

PHP 5 File Upload

PHP allows uploading files. In order to upload files in a specific way you can set up
certain limitations. We can do this by editing the file called “php.ini” and changing the value of
file_uploads to “on”in “php.ini”configuration file.

file_uploads = On

File Upload Create HTML Form

After we allow file uploads, we can get to creating an HTML form for uploads:

<!DOCTYPE html>
<html>
<body>

64
<form action="upload.php" method="post"enctype="multipart/form-data">
Select the image you want to upload:
<input type="file" name="file_to_upload"id="file_to_upload">
<input type="submit" value="image upload"name="submit">
</form>

</body>
</html>

To use file upload forms effectively we must remember a few things:

 We must use the POST method (which we assign the form tag as an attribute) whenever
uploading through forms.
 We must also assign enctype=”multipart/form-data” among its attributes. This allows the
browser to identify the encoding type in order to upload files.

Note: The attribute type=”file” of the tag <input> displays the input field as a file-select control
next to a “Browse” button

PHP 5 File Upload PHP Script

The code for file uploads is described in the “upload.php” file:

Example
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file_to_upload"]["name"]);
$upload_ok = 1;
$image_file_type = pathinfo($target_file,PATHINFO_EXTENSION);
// checking if image file is accessible
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file_to_upload"]["tmp_name"]);
if($check !== false) {
echo "The file you picked is an image - " . $check["mime"] . ".";
$upload_ok = 1;
} else {
echo "The file you picked is not image.";
$upload_ok = 0;
}
}
?>

65
PHP script explained:

 $target_dir = “uploads/” – Directs the server to a directory.


 $target_file Declares the path to the file you want to upload.
 $upload_ok=1 This will be used to determine whether the upload was successful.
 $image_file_type This will be used to check what the file extension is.
 Lastly, we must check if the file is valid.

Regular expressions
Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside a another string, you can
replace one string by another string and you can split a string into many chunks.

PHP offers functions specific to two sets of regular expression functions, each corresponding to a
certain type of regular expression. You can use any of them based on your comfort.

 POSIX Regular Expressions


 PERL Style Regular Expressions

POSIX Regular Expressions

The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic
expression: various elements (operators) are combined to form more complex expressions.

The simplest regular expression is one that matches a single character, such as g, inside strings
such as g, haggle, or bag.

Lets give explanation for few concepts being used in POSIX regular expression. After that we
will introduce you with regular expression related functions.

Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
Sr.No Expression & Description
1 [0-9] It matches any decimal digit from 0 through 9.
2 [a-z] It matches any character from lower-case a through lowercase z.
3 [A-Z] It matches any character from uppercase A through uppercase Z.
4 [a-Z] It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from
b through v.

66
Quantifiers

The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character having a specific connotation. The +, *, ?, {int.
range}, and $ flags all follow a character sequence.

Sr.No Expression & Description


1 p+ It matches any string containing at least one p.
2 p* It matches any string containing zero or more p's.
3 p? It matches any string containing zero or more p's. This is just an alternative way
to use p*.
4 p{N} It matches any string containing a sequence of N p's
5 p{2,3} It matches any string containing a sequence of two or three p's.
6 p{2, } It matches any string containing a sequence of at least two p's.
7 p$ It matches any string with p at the end of it.
8 ^p It matches any string with p at the beginning of it.

PHP currently offers following functions for searching strings using POSIX-style regular
expressions

Sr.No Function & Description


1 ereg() The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.
int ereg ( string $pattern , string $string [, array &$regs ] ) Searches a string for matches to the regular
expression given in pattern in a case-sensitive way. Alternatives to this function include:
preg_match()
2 ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces
pattern with replacement if found.
string ereg_replace ( string $pattern , string $replacement , string $string ) This function scans string
for matches to pattern, then replaces the matched text with replacement.
3 eregi() The eregi() function searches throughout a string specified by pattern for a string specified
by string. The search is not case sensitive.
4 eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the
search for pattern in string is not case sensitive.

Note: ereg functions are no longer included in PHP6


PERL Style Regular Expressions
Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be
used almost interchangeably with the Perl-style regular expression functions. In fact, you can use
any of the quantifiers introduced in the previous POSIX section.

67
Lets give explanation for few concepts being used in PERL regular expressions. After that we
will introduce you wih regular expression related functions.
PHP offers following functions for searching strings using Perl-compatible regular expressions –

Sr.No Function & Description


1 preg_match() The preg_match() function searches string for pattern, returning true if pattern
exists, and false otherwise.
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0
]]] ) Searches subject for a match to the regular expression given in pattern.
2 preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags =
PREG_PATTERN_ORDER [, int $offset = 0 ]]] ) Searches subject for all matches to the regular
expression given in pattern and puts them in matches in the order specified by flags
3 preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int
&$count ]] )
Searches subject for matches to pattern and replaces them with replacement.
4 preg_grep() The preg_grep() function searches all elements of input_array, returning all
elements matching the regexp pattern.
array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )
Returns the array consisting of the elements of the input array that match the given pattern.

Example1:
function chkURL($url) {
$pattern = '^www\.[a-z]+\.com$';
return(preg_match('/'.$pattern.'/', $url));
//return(ereg($pattern, $url));
}
$urls_to_test = array('www.google.com', 'www.java.sun.com', 'www.zend.com');
while($testURL = array_pop($urls_to_test)) {
if(chkURL($testURL))
print("<br>\"$testURL\" is VALID");
else
print("<br>\"$testURL\" is inValid");
}
Example2:
<?php
// create a string
$string = 'big’;
// Search for a match
echo preg_match("/b[aeiu]g/", $string);
?>
The above code will return 1. This is because preg_match() found a match. This code would also match
the string 'bag' 'beg' 'big' but not match the string 'beg'.

Configuring PHP for database support


68
This can be done by Installing and Configuring the XAMPP Package (Open Source) .The section
describes how to download, install, and configure the XAMPP package.
1. Download the XAMPP installer package. (XAMPP Lite does not include XDebug.)
2. When the download is completed, run the .exe file.
3. You are given the option to install the Apache server and the MySQL database server as
services. If you install the Apache Server and MySQL as services, you will not have to
start them manually through the XAMP Control Panel. Note that you have the option to
install or uninstall these services in the XAMPP Control Panel.
4. If you are using the self-extracting archive, after the archive is extracted, run the file
setup-xampp.bat to configure the components of the package. (The XAMPP installer runs
this file automatically.)
5. After configuration, open the XAMP Control Panel. (You can open it manually by
running the file XAMPP_HOME/xampp-control.exe or from the Xampp Control Panel
icon that is automatically placed on your desktop.) When you open the XAMPP Control
Panel, note that the modules that are installed as services are already running.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and
variables that your application will need to call in order to carry out its desired task. In the case
of PHP applications that need to communicate with databases the necessary APIs are usually
exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out
tasks, with the object-oriented API you instantiate classes and then call methods on the resulting
objects. Of the two the latter is usually the preferred interface, as it is more modern and leads to
better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API
options available. This document discusses what is available and how to select the best solution
for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your
application to connect to the MySQL database server. MySQL provides connectors for a variety
of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP
code to perform such activities as connecting to the database server, querying the database and
other database-related functions. Software is required to provide the API that your PHP
application will use, and also handle the communication between your application and the
database server, possibly using other intermediate libraries where necessary. This software is
known generically as a connector, as it allows your application to connect to a database server.

69
What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server.
The driver may also call a library, such as the MySQL Client Library or the MySQL Native
Driver. These libraries implement the low-level protocol used to communicate with the MySQL
database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of
several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver,
which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In
the MySQL-related documentation the term "driver" is reserved for software that provides the
database-specific part of a connector package.

What is an Extension?

In the PHP documentation you will come across another term - extension. The PHP code consists
of a core, with optional extensions to the core functionality. PHP's MySQL-related extensions,
such as the mysqli extension, and the mysql extension, are implemented using the PHP extension
framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used
programmatically. However, some extensions which use the PHP extension framework do not
expose an API to the PHP programmer. The PDO MySQL driver extension, for example, does
not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may
not necessarily expose an API to the programmer.

What are the main PHP API offerings for using MySQL?

There are three main API options when considering connecting to a MySQL database server.
Each has its own advantages and disadvantages.
 PHP's MySQL Extension
 PHP's mysqli Extension
 PHP Data Objects (PDO)

What is PHP's MySQL Extension?

This is the original extension designed to allow you to develop PHP applications that interact
with a MySQL database. The mysql extension provides a procedural interface and is intended for
use only with MySQL versions older than 4.1.3. This extension can be used with versions of
MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.

The mysql extension source code is located in the PHP extension directory ext/mysql.

70
What is PHP's mysqli Extension?

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was
developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer.
The mysqli extension is included with PHP versions 5 and later.

The mysqli extension has a number of benefits, the key enhancements over the mysql extension
being:
 Object-oriented interface
 Support for Prepared Statements ,Multiple Statements , Transactions
 Enhanced debugging capabilities and Embedded server support

What is PDO?

PHP Data Objects, or PDO, is a database abstraction layer specifically for PHP applications.
PDO provides a consistent API for your PHP application regardless of the type of database
server your application will connect to. In theory, if you are using the PDO API, you could
switch the database server you used, from say Firebird to MySQL, and only need to make minor
changes to your PHP code. Other examples of database abstraction layers include JDBC for Java
applications and DBI for Perl.

While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is
that it doesn't allow you to use all of the advanced features that are available in the latest versions
of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple
Statements. PDO is implemented using the PHP extension framework, its source code is located
in the directory ext/pdo.

What is the PDO MYSQL driver?

The PDO MYSQL driver is not an API as such, at least from the PHP programmer's perspective.
In fact the PDO MYSQL driver sits in the layer below PDO itself and provides MySQL-specific
functionality. The programmer still calls the PDO API, but PDO uses the PDO MYSQL driver to
carry out communication with the MySQL server.

The PDO MYSQL driver is implemented using the PHP extension framework. Its source code is
located in the directory ext/pdo_mysql. It does not expose an API to the PHP programmer.

Wrapper classes just make their child class easier to use for a particular circumstance. A lot of
libraries are written to cover a wide variety of situations and therefore become cumbersome and
complex to use. A lot of projects will create a wrapper for the library to make it easier to use.
Eg: PDO

Maintaining State

The Web Server does not remember your past transactions. If you have a sequence of
transactions where the action of the present transaction is dependent on a past transaction then

71
the present transaction must have some "memory" of the past transaction. There must be some
mechanism in place to transfer information from the past transaction to the present. This transfer
of information can be done in 3 ways:

 Hidden Variables
 Cookies
 State Files

Hidden Variables

Hidden variables are name-value pairs that are embedded in a form that can be checked by the
script processing form data on the server side. As the name imples hidden variables are not
displayed when the form is rendered on the client side.

Let us consider the following transaction sequence - an order form is displayed, once you place
the order a confirmation page is displayed, when you confirm the order a thank-you page is
displayed. A hidden variable page keeps track of which page is to be displayed. Here is the
application logic:

if ($_POST["page"] == "confirm")
confirmPage();
elseif ($_POST["page"] == "order")
orderPage();
else
orderForm();
When the script is first called the variable page is not set and hence the function orderForm() is called.
After that the confirmPage() function is called and finally the function orderPage(). Here is how the
transaction sequence works. This is the actual code.

Cookies

A cookie is a small piece of data in the form of a name-value pair that is sent by a Web server
and stored by the browser on the client machine. This information is used by the application
running on the server side to customize the web page according to the past history of transactions
from that client machine.

When a client browser makes a request for a web page from a server, it first checks to see if there
are any cookies present from that server in its cookie folder. If there are any cookies then those
cookies are sent to the web server along with the request for the page. The application program
on the server side reads the cookies and tailors the web page accordingly. It may reset the
cookies according to the present transaction.

A transient cookie is there just for the session. A persistent cookie can exist for a long time
(order of years). The application program sets the time to live for the cookie. One way of
deleting a cookie is to set its time to live to a time in the past.

A cookie is a name-value pair. In its simplest form to set a transient cookie the function
setcookie() is used with the name-value pair as parameters:
72
setcookie ("some_name", "some_value");
To set a permanent cookie the expiration time must be given. One way is to read the current time and then
add an increment to it in seconds. For example to set a cookie that lasts for a year the following command
will work:

setcookie ("some_name", "some_value", time()+3600*24*365);

The setcookie() function must be called before any printed output occurs. The cookie must be
written as part of the HTTP header.

All cookies from that url are sent back to the server when the browser requests a web page. The
associative array $_COOKIE holds all the name value pairs. To read the value for a particular
cookie do:

$value = $_COOKIE["some_name"];

State Files

In PHP name-value pairs can be stored in state files on the server side. A session can be started
by using the command

session_start();
before making any printed output. A unique session id is generated. The script need not know the id but
its value can be retrieved from

$id = session_id();
Session ids can be passed as hidden variables or stored as cookies between transactions. To close a
session do

session_destroy();

The name-value pairs are stored in an array called $_SESSION. To register a name-value pair
do:

$_SESSION["some_name"] = some_value;
To extract or retrieve the value from a session variable:

$value = $_SESSION["some_name"];

What is Cookie?
A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer. Once a cookie has been set, all page requests that follow return the cookie name and
value. A cookie can only be read from the domain that it has been issued from. For example, a
cookie set using the domain www.cavalier.com can not be read from the domain
cavalieranimation.com.

A cookie created by a user can only be visible to them. Other users cannot see its value.

73
Most web browsers have options for disabling cookies, third party cookies or both.

Why and when to use Cookies?


 Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer. The path where the cookies are stored depends
on the browser. Internet Explorer usually stores them in Temporal Internet Files folder.
 Personalizing the user experience – this is achieved by allowing users to select their
preferences. The page requested that follow are personalized based on the set preferences
in the cookies.
 Tracking the pages visited by a user

Syntax for Creating Cookies


setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);
HERE,
 Php“setcookie” is the PHP function used to create the cookie.
 “cookie_name” is the name of the cookie that the server will use when retrieving its value from
the $_COOKIE array variable. It’s mandatory.
 “cookie_value” is the value of the cookie and its mandatory
 “[expiry_time]” is optional; it can be used to set the expiry time for the cookie such as 1 hour.
The time is set using the PHP time() functions plus or minus a number of seconds greater than 0
i.e. time() + 3600 for 1 hour.
 “[cookie_path]” is optional; it can be used to set the cookie path on the server. The forward slash
“/” means that the cookie will be made available on the entire domain. Sub directories limit the
cookie access to the subdomain.
 “[domain]” is optional, it can be used to define the cookie access hierarchy i.e.
www.cookiedomain.com means entire domain while www.sub.cookiedomain.com limits the
cookie access to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a
subdomain of a subdomain as long as the total characters do not exceed 253 characters.
 “[secure]” is optional, the default is false. It is used to determine whether the cookie is sent via
https if it is set to true or http if it is set to false.
 “[Httponly]” is optional. If it is set to true, then only client side scripting languages i.e.
JavaScript cannot access them.

Note: the php set cookie function must be executed before the HTML opening tag.

<?php
setcookie("user_name", "Guru99", time()+ 60,'/'); // expires after 60 seconds
echo 'the cookie has been set for 60 seconds';
?>
OUTPUT:
the cookie has been set for 60 seconds

74
Retrieving the Cookie value
Create another file named “cookies_read.php” with the following code.

<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>

Note: $_COOKIE is a PHP built in super global variable.

It contains the names and values of all the set cookies.

The number of values that the

$_COOKIE array can contain depends on the memory size set in php.ini.

The default value is 1GB.

Let’s assume you have saved your PHP files in php folder.

 Step 1 – open your web browser and enter the URL


http://localhost/phptuts/cookies.php
Note: Only an empty array has been displayed
 Step 2 – Browser to the URL http://localhost/phptuts/cookies.php
 Step 3 – Switch back to the first tab then click on refresh button to see the results

Delete Cookies
If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that
has already passed. Create a new filed named cookie_destroy.php with the following code
<?php

setcookie("user_name", "Guru99", time() - 360,'/');

?>
Repeat steps 1 through to 3 from the above section on retrieving cookie values.
Open the URL http://localhost/phptuts/cookie_destroy.php
Switch to the URL http://localhost/phptuts/cookies_read.php what results does it display?

What is a Session?
 A session is a global variable stored on the server.
 Each session is assigned a unique id which is used to retrieve stored values.

75
 Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser does
not support cookies, the unique php session id is displayed in the URL
 Sessions have the capacity to store relatively large data compared to cookies.
 The session values are automatically deleted when the browser is closed. If you want to
store the values permanently, then you should store them in the database.
 Just like the $_COOKIE array variable, session variables are stored in the $_SESSION
array variable. Just like cookies, the session must be started before any HTML tags.
 You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
 You want to pass values from one page to another.
 You want the alternative to cookies on browsers that do not support cookies.
 You want to store global variables in an efficient and more secure way compared to
passing them in the URL
 You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.

Why and when to use Sessions?


 You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
 You want to pass values from one page to another.
 You want the alternative to cookies on browsers that do not support cookies.
 You want to store global variables in an efficient and more secure way compared to
passing them in the URL
 You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.

Creating a Session
In order to create a session, you must first call the PHP session_start function and then store
your values in the $_SESSION array variable.

Let’s suppose we want to know the number of times that a page has been loaded, we can use a
session to do that.

The code below shows how to create and retrieve values from sessions

<?php

76
session_start(); //start the PHP_session function

if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];

?>

OUTPUT

You are visitor number 1

Destroying Session Variables


The session_destroy() function is used to destroy the whole Php session variables.

If you want to destroy only a session single item, you use the unset() function.

<?php

session_destroy(); //destroy entire session

?>

Session_destroy removes all the session data including cookies associated with the session.

Unset only frees the individual session variables.

Other data remains intact.

Difference between Cookies and Session


 Cookies are small files saved on the user’s computer
 Cookies can only be read from the issuing domain
 Cookies can have an expiry time, if it is not set, then the cookie expires when the browser
is closed
 Sessions are like global variables stored on the server
 Each session is given a unique identification id that is used to track the variables for a
user.
 Both cookies and sessions must be started before any HTML tags have been sent to the
browser.

77
Populating FORMS

One of the best features of PHP is possibility to respond to user queries or data submitted from
HTML forms. You can process information gathered by an HTML form and use PHP code to
make decisions based off this information to create dynamic web pages.

The HTML Form

Before you can process the information, you need to create an HTML form that will send
information to your PHP script. There are two methods for sending data: POST and GET. These
two types of sending information are defined in your HTML form element's method attribute.
Also, you must specify the location of the PHP file that will process the information.

Below is an HTML form that will send the data using the POST method. Information sent from a
form with the POST method is invisible to others and has no limits on the amount of information
to send.

form.html

<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Registration Form</h2>
<form action="registration_form.php" method="POST"> First name:

<input type="text" name="firstname"> <br> Last name:

<input type="text" name="lastname">

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">


</form>
</body>
</html>
Output in browser http://localhost/form.html

78
HERE,

 <form…>…</form> are the opening and closing form tags


 action="registration_form.php" method="POST"> specifies the destination URL and the
submission type.
 First/Last name: are labels for the input boxes
 <input type=”text”…> are input box tags
 <br> is the new line tag
 <input type="hidden" name="form_submitted" value="1"/> is a hidden value that is used
to check whether the form has been submitted or not
 <input type="submit" value="Submit"> is the button that when clicked submits the form
to the server for processing

Submitting the form data to the server

OR

Retrieving / Capturing Form Data with PHP on submission


The action attribute of the form specifies the submission URL that processes the data. The
method attribute specifies the submission type.

PHP POST method


 This is the built in PHP super global array variable that is used to get values submitted
via HTTP POST method.
 The array variable can be accessed from any script in the program; it has a global scope.
 This method is ideal when you do not want to display the form post values in the URL.
 A good example of using post method is when submitting login details to the server.

It has the following syntax.


<?php
$_POST['variable_name']; Eg: $_POST['firstname']
?>
HERE,
 “$_POST[…]” is the PHP array
 “'variable_name'” is the URL variable name.

PHP GET method


 This is the built in PHP super global array variable that is used to get values submitted
via HTTP GET method.
 The array variable can be accessed from any script in the program; it has a global scope.
 This method displays the form values in the URL.
 It’s ideal for search engine forms as it allows the users to book mark the results.

It has the following syntax.


<?php

79
$_GET['variable_name']; Eg: $_GET['firstname']
?>
HERE,
 “$_GET[…]” is the PHP array
 “'variable_name'” is the URL variable name.

GET vs POST Methods

POST GET
Values not visible in the URL Values visible in the URL
Has not limitation of the length of the values Has limitation on the length of the values
since they are submitted via the body of HTTP usually 255 characters. This is because the
values are displayed in the URL. Note the upper
limit of the characters is dependent on the
browser.
Has lower performance compared to Php_GET Has high performance compared to POST
method due to time spent encapsulation the method dues to the simple nature of appending
Php_POST values in the HTTP body the values in the URL.
Supports many different data types such as Supports only string data types because the
string, numeric, binary etc. values are displayed in the URL
Results cannot be book marked Results can be book marked due to the visibility
of the values in the URL

The below diagram shows the difference between get and post

Note: $_REQUEST method Contains the values of both the $_GET and $_POST variables as well as the
values of the $_COOKIE superglobal variable.

80
Error Logging

The error_log() function sends an error message to a log, to a file, or to a mail account. Error handling is
the process of catching errors raised by your program and then taking appropriate action. If you
would handle errors properly then it may lead to many unforeseen consequences. Its very simple
in PHP to handle an errors.

There are two methods for viewing PHP errors that occur while running your website. You can either
display errors directly on your website (viewable from any web browser) or enable error logging to write
the errors to a specified file (viewable inside a text file).

Editing the php.ini to Display Errors

While your site is live, the php.ini file should have display_errors disabled for security reasons.
However, for the development environment, display_errors can be enabled for troubleshooting.
Displaying errors should be disabled while the site is live, to protect sensitive information and
not interfere with the format of your website pages. When display_errors is On, your site's pages
will display any PHP errors encountered when loading your website in a browser.

How to control error reporting and turn display_errors On and Off:

Find the "Error handling and logging" section in the php.ini. In order to display or log errors,
you need to enable error_reporting by removing the ( ; ) from in front to the line. You can
disable error_reporting by adding a ( ; ) in front of the line. Refer to the code below:

Error reporting disabled:

; - Show all errors, except for notices


;
;error_reporting = E_ALL & ~E_NOTICE
;

Error reporting enabled to specifically report all errors, but not notices:

; - Show all errors, except for notices


;
error_reporting = E_ALL & ~E_NOTICE
;

Next you can set the display_errors variable to On or Off to either show the errors on your
website or not. Look for the display_errors line in the php.ini file and set it to On to display
errors or Off to turn not display errors. The code looks like the following:

Display errors:

display_errors = On

81
Do not display errors:

display_errors = Off

The following table refer for the available few types of errors:

1 E_ERROR Fatal run-time errors. Execution of the script is halted

Eg: <?php
function func1()
{
echo "PHP";
}
func2();
?>
Output
In the above code we defined a function func1 but we call another function func2 i.e. func2 is not defined. So a
fatal error will be produced that stops the execution of the script.
2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted

<?php
$file=fopen("welcome.txt","r");
?>

Warning: fopen(welcome.txt) [function.fopen]: failed to open stream


3 E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser.
Also called as Syntax errors.

Eg: PHP Parse error: syntax error, unexpected '{' in index.php on line 20
E_NOTICE run-time notices (these are warnings which often result from a bug in your
4 code, but it's possible that it was intentional (e.g., using an uninitialized variable and relying
on the fact it's automatically initialized to an empty string)
<?php
$a="Vineet kumar saini";
echo $b;
?>
Output
In the above code we defined a variable which named $a. But we call another variable i.e. $b, which is not
defined. So there will be a notice error produced but execution of the script does not stop
5 E_ALL All errors and warnings

Environment variables
$_ENV is a superglobal that contains environment variables. An associative array of variables
passed to the current script via the environment method. Environment variables are provided by
the shell under which PHP is running, so they may vary according to different shells.
Environment variables for configuration are today’s best practice for application setup – database

82
credentials, API Keys, secrets and everything varying between deploys are now exposed to the
code via the environment, instead of configuration files or worse, directly hard-coded.

Use and examples

You can access these variables using the $_SERVER and $_ENV arrays which are PHP
superglobal arrays. They do not have to be declared as global variables.

$_SERVER["SITE_HTMLROOT"]
The full path to your site's document root, returns output like /home/00000/domains/example.com/html.

In .htaccess

You can also have Apache set environment variables for use in your scripts, via a .htaccess file,
using SetEnv or in Rewrite rules. These variables must start with 'HTTP_' for security purposes.

SetEnv HTTP_MY_VARIABLE "my value"

Changing execution by redirecting to Other URLs

We have different methods to redirect URLs in PHP. There are times when you decide to write a
redirect script in PHP. The following are the advantages of using creating such a script in PHP:

1.) PHP is a server side scripting language; the redirect script will be executed on your server and
not on your visitors browser. This is a non-client/browser dependent approach. Some redirects
are client side, such as JavaScript and will fail if the user wishes to disable Java Scripting
functionality.

2.) It is a more flexible and versatile approach; you can execute several types of redirects in PHP
that you can’t with other methods. For example, the following are the most commonly types of
redirects that can be done in PHP:
a.) 301 permanent redirection status.
b.) 302 temporary redirection status.
c.) Refresh type (header() function)

There are still other redirection header status that you can do with PHP, but we will focus on the
above types of redirecting URLs with the help of header() function.

PHP Header() Function

Redirecting URLs in PHP centers around the PHP Header() function. For example, suppose you
want to redirect to this URL http://www.cavalier.com/target.php. In the originating PHP page,
you will simply call this script:

83
<?php
header(‘Location: http://www.cavalier.com/target.php’);
?>

This is the most basic form and may not be appropriate in all cases or in your own
implementation. Anyway for the purpose of introducing you to redirecting URLs in PHP, try this
simple experiment in your XAMPP localhost:

1.) Open a text editor and type this code:

<?php
echo "Hi this is codex-m";
?>

Save it as targetpage.php and put it inside the htdocs folder.

2.) Open another blank text file and enter this code:

<?php
header(‘Location: http://localhost/targetpage.php’);
?>

Save it as originatingpage.php and put it also in the htdocs folder.

3.) Now launch your web browser. In the browser address bar, type:
http://localhost/originatingpage.php

4.) You will notice that after you press enter. This URL: http://localhost/originatingpage.php
redirects to http://localhost/targetpage.php and the content you see is the targetpage.php content
which is “Hi this is codex-m”.

//Conditional check to redirect


if ($currentpageurl=="http://www.cavalier.org/301redirecttest.php") {

//URL match, do 301 redirect - Permenant Redirection


header(‘Location: http://www.cavalier.org/’,TRUE,301);
exit();
}

Embedding java script with PHP

Java script can be inserted by embedding <script> tag in a php script as follows:

1) <?php ?>
<script language='javascript'>
......

84
</script>
<?php ?>

2) <?php
echo " <script language='javascript'>
</script>";
?>
3) <?php
echo ‘ <script language=”javascript”>
</script>’;
?>

Sample Program

<?php
$a=rand(1,100);
if($a%2==0){
echo "<script>alert("Number is Even");</script>";
}
else {
echo "<script>alert("Number is Odd");</script>";
}
?>
Here,

1. The code will get executed in the server


2. A random number between 1 to 100 will be generated.
3. Depending upon whether it is ODD or EVEN the JS code will be sent to the browser.
4. Ones the browser receives the JS code it just executes it.

Note: JavaScript can be Enabled / Disabled by user in Browser.

PHP 5 FTP Functions

The FTP functions give client access to file servers through the File Transfer Protocol (FTP).

The FTP functions are used to open, login and close connections, as well as upload, download,
rename, delete, and get information on files from file servers. Not all of the FTP functions will
work with every server or return the same results. The FTP functions became available with PHP
3.

The following table lists few of the functions below:

Function Description
ftp_chdir() Changes the current directory on the FTP server
ftp_chmod() Sets permissions on a file via FTP
ftp_close() Closes an FTP connection

85
ftp_connect() Opens an FTP connection
ftp_delete() Deletes a file on the FTP server
ftp_exec() Executes a command on the FTP server
ftp_get() Downloads a file from the FTP server
ftp_login() Logs in to the FTP connection
ftp_mkdir() Creates a new directory on the FTP server
ftp_put() Uploads a file to the FTP server
ftp_pwd() Returns the current directory name
ftp_quit() An alias of ftp_close()
ftp_rename() Renames a file or directory on the FTP server
ftp_rmdir() Deletes an empty directory on the FTP server

PHP HTTP Introduction


The HTTP functions let you manipulate information sent to the browser by the Web server,
before any other output has been sent. The HTTP functions are part of the PHP core. There is no
installation needed to use these functions. The commonly used PHP 5 HTTP functions are:

Function Description

header() Sends a raw HTTP header to a client


headers_list() Returns a list of response headers sent (or ready to send)
headers_sent() Checks if / where the HTTP headers have been sent

Showing different content to different Browsers

A website is just a set of instructions describing how a site should look. It's up to the browser to
render it by reading the entire code of your website and producing a certain output. There are,
however, differences in the code interpretation and different browsers will render the same page
slightly differently. A good website should look the same and all its features should work in any
browser. Unfortunately, there is no easy solution for that. You should check the specificities of
each browser that fails to display your website correctly and make the necessary adjustments to
your code. Few reasons for this incompatibility are:

 Hardware Issues

A computer's graphics card allows users to adjust brightness, digital vibrance, contrast, image
sharpness, gamma, and other settings that affect color. Depending on the settings, a user will see
different colors or tones for all elements on a web page, including images and fonts. The display
resolution setting of a monitor affects the appearance of a web page as well. As a rule, we
design sites to display optimally on a setting of 1024x768 and up. Pages will not display
optimally at lower resolutions.

86
 Installed Fonts
Websites are designed, or should be, with what are called "font stacks." What this does is create
a default font for display; if a particular user doesn't have that font loaded on his/her computer,
the display defaults to the next font in the stack, and so forth.

 Browsers
Browser differences are probably the biggest culprit in web display inconsistency. Every browser
has a "layout engine" that interprets a site's CSS code and converts it into a visual image of a
web page. Most display issues occur in various versions of Internet Explorer, which has a still-
hefty 20% browser market share. Common problems include few like:

 Rounded corners appearing squared off in IE


 Shadows and rollover effects being ignored in IE

How to detect browser in PHP?

PHP's $_SERVER global variable holds browser's ID information in HTTP_USER_AGENT


key: $_SERVER['HTTP_USER_AGENT'].

<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];

if (preg_match('/MSIE/i', $user_agent)) {
echo "Internet Explorer";
} else {
echo "Non-IE Browser";
}
?>

Better alternative would be also to use PHP function get_browser:


<?php
$browser = get_browser(null, true);
print_r($browser);
?>

Getting Visitors IP Address in PHP


Getting a visitors IP address can be important for a lot of reasons, for example, logging, geo
targeting, redirecting the user and so on. All of the IP relevant informations can be found in the
$_SERVER array. The simplest way to get the visitors IP address is as simple as the following
code, by reading the REMOTE_ADDR field:
<?php $ip = $_SERVER['REMOTE_ADDR'];?>

87
UNIT - 3
A Database is a separate application that stores a collection of data. Each database has one or
more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

Other kinds of data stores can also be used, such as files on the file system or large hash tables in
memory but data fetching and writing would not be so fast and easy with those types of systems.

A Relational DataBase Management System (RDBMS) is a software that −


 Enables you to implement a database with tables, columns and indexes.

88
 Guarantees the Referential Integrity between rows of various tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from various tables.

History

MySQL was created by a Swedish company, MySQL AB, founded by David Axmark, Allan
Larsson and Michael "Monty" Widenius. Original development of MySQL by Widenius and
Axmark began in 1994. The first version of MySQL appeared on 23 May 1995. It was initially
created for personal usage from mSQL based on the low-level language ISAM, which the
creators considered too slow and inflexible. They created a new SQL interface, while keeping the
same API as mSQL. By keeping the API consistent with the mSQL system, many developers
were able to use MySQL instead of the (proprietarily licensed) mSQL antecedent.

Overview of MY SQL,what is my SQL?


MySQL is a relational database management system (RDBMS) released under the GNU General
Public License (GPL). It is one of the most widely used open-source database systems, and is
compatible with a multitude of website applications. MySQL is a fast, easy-to-use RDBMS
being used for many small and big businesses. MySQL is developed, marketed and supported by
MySQL AB, which is a Swedish company. MySQL is becoming so popular because of many
good reasons −
 MySQL is released under an open-source license. So you have nothing to pay to use it.
 MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
 MySQL uses a standard form of the well-known SQL data language.
 MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
 MySQL works very quickly and works well even with large data sets.
 MySQL is very friendly to PHP, the most appreciated language for web development.
 MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
 MySQL is customizable. The open-source GPL license allows programmers to modify
the MySQL software to fit their own specific environments.

Connecting & Disconnecting From the MySQL Server

 From the command line (cmd), connecting to MYSQL may require knowledge of the
host, the username and the password that are provided by the hosting company that you
are using.

89
mysql -h host -u username -p

 The above line starts out by naming the program we want to run (MYSQL). The "-h" part
identifies the host, which will be provided by your hosting company and typed in the
place of "host". The "-u" identifies the username, which is also provided by the hosting
company and will replace the word "username". The "-p" part states that there is a
password that needs to be entered, but notice that it is not entered here (for security
reasons). Instead, after typing in this line and hitting the <enter> key, you will be
prompted with something like this:

Enter password:

 ...And there you type in your password, where it will either not show up as you type it in,
or show up as a series of asterisks * that keep passersby from reading your password.
(unless they watched your fingers as you typed it in!)
 After typing in your password and hitting <enter> again, you will be presented with a
welcome screen similar to this:

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 25338 to server version: 5.1.55-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

 And you are ready to type in commands that can create databases, add information,
update information, etc.
 All commands that you type in will show up after the "mysql>".
 When you are finished, simply type in "quit" and you will be signed out and returned to
the original command prompt.

mysql> quit

Creating and Selecting a Database

If the administrator creates your database for you when setting up your permissions, you can
begin using it. Otherwise, you need to create it yourself:

mysql> CREATE DATABASE sampleDatabase;

Under Unix, database names are case-sensitive (unlike SQL keywords), so you must always refer
to your database as sampleDatabase, not as SampleDatabase, SAMPLEDATABASE, or some other
variant. This is also true for table names. (Under Windows, this restriction does not apply,
although you must refer to databases and tables using the same lettercase throughout a given

90
query. However, for a variety of reasons, the recommended best practice is always to use the
same lettercase that was used when the database was created.)

Creating a database does not select it for use; you must do that explicitly. To make sampleDatabase
the current database, use this statement:

mysql> USE sampleDatabase


Database changed

CREATE TABLE

The MySQL CREATE TABLE command is used to create a new table into the database. A table
creation command requires three things:

 Name of the table


 Names of fields
 Definitions for each field

Syntax: Following is a generic syntax for creating a MySQL table in the database.

1. CREATE TABLE table_name (column_name column_type...);

Example:

Here, we will create a table named "cus_tbl" in the database "customers".

CREATE TABLE cus_tbl(


cus_id INT NOT NULL AUTO_INCREMENT,
cus_firstname VARCHAR(100) NOT NULL,
cus_surname VARCHAR(100) NOT NULL,
PRIMARY KEY ( cus_id )
);

LOADING data into a table

MySQL LOAD statement populates a table.

Suppose the user have a .txt file name 'pub.txt' in a folder of its own, containing 1 record per line
and separated by tabs and arranged in order as the columns listed in the table. You can use
LOAD statement to populate the table. For missing values, the user can use NULL values and
that should be represented by ‘\N’ in the text file.

Syntax:

LOAD DATA LOCAL INFILE '[path/][file_name]' INTO TABLE [table_name ];

Arguments

91
Name Description
path The address of the file.
file_name The name of the .txt file.
table_name The table where the data will be loaded.

Example:

In the following code, the content of the text file pub.txt will be loaded in the publisher table.

The path of the file should be mentioned.

The text file contains the row like -

P002<tab>BPP Publication<tab>Mumbai<tab>India<tab>New Delhi<tab>10<tab>1985-10-01

Code:

LOAD DATA LOCAL INFILE 'pub.txt' INTO TABLE publisher;

Retrieving information from a table


The Structured Query Language offers database users a powerful and flexible data retrieval
mechanism -- the SELECT statement.

The General Form of the SELECT Statement


SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy;

The first line of the statement tells the SQL processor that this command is a SELECT statement
and that we wish to retrieve information from a database. The select_list allows us to specify the
type of information we wish to retrieve.

The FROM clause in the second line specifies the specific database table(s) involved and the
WHERE clause gives us the capability to limit the results to those records that meet the
specified condition(s).

Retrieving an Entire Table


SELECT * FROM pet;

The asterisk (*) appearing in the select_list is a wildcard used to inform the database that we
would like to retrieve information from all of the columns in the employee's table identified in
the FROM clause. We wanted to retrieve all of the information in the database, so it wasn't
necessary to use a WHERE clause to restrict the rows selected from the table.

92
+----------+--------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+----------+--------+---------+------+------------+------------+
| Fluffy | Harold | cat | f | 1993-02-04 | NULL |
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
| Fang | Benny | dog | m | 1990-08-27 | NULL |
| Bowser | Diane | dog | m | 1979-08-31 | 1995-07-29 |
| Chirpy | Gwen | bird | f | 1998-09-11 | NULL |
| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL |
| Slim | Benny | snake | m | 1996-04-29 | NULL |
| Puffball | Diane | hamster | f | 1999-03-30 | NULL |
+----------+--------+---------+------+------------+------------+

Selecting Particular Rows

Typically you don't want to see the entire table, particularly when it becomes large. Instead,
you're usually more interested in answering a particular question, in which case you specify
some constraints on the information you want. Let's look at some selection queries in terms of
questions about your pets that they answer.

You can select only particular rows from your table. For example, if you want to verify the
change that you made to Bowser's, select Bowser's record like this:

mysql> SELECT * FROM pet WHERE name = 'Bowser';

Selecting Particular Columns

If you do not want to see entire rows from your table, just name the columns in which you are
interested, separated by commas. For example, if you want to know when your animals were
born, select the name and birth columns:

mysql> SELECT name, birth FROM pet;

To find out who owns pets, use this query:

mysql> SELECT owner FROM pet;

Getting Information about Databases and Tables


MySQL provides a SHOW statement that has several variant forms that display information about
databases and the tables in them. SHOW is helpful for keeping track of the contents of your
databases and for reminding yourself about the structure of your tables. You can also use SHOW
prior to issuing ALTER TABLE; it's often easier to figure out how to specify a change to a column
after you determine the column's current definition.

The SHOW statement can be used to obtain information about several aspects of your databases
and tables:

93
 List the databases managed by the server:

SHOW DATABASES;

 List the tables in the current database or in a given database:

SHOW TABLES;
SHOW TABLES FROM db_name;

 Note that SHOW TABLES doesn't show TEMPORARY tables.


 Display information about columns or indexes in a table:

SHOW COLUMNS FROM tbl_name;


SHOW INDEX FROM tbl_name;
 The DESCRIBE tbl_name and EXPLAIN tbl_name statements are synonymous with SHOW
COLUMNS FROM tbl_name.

MySQL Data Types


A database table contains multiple columns with specific data types such as numeric or string.
MySQL provides more data types other than just numeric or string. Each data type in MySQL
can be determined by the following characteristics:

 The kind of values it represents.


 The space that takes up and whether the values is a fixed-length or variable length.
 The values of the data type can be indexed or not.

String Datatypes
The following are the String Datatypes in MySQL:

Data Type Maximum Size Explanation


Syntax
CHAR(size) Maximum size of 255 Where size is the number of characters to store. Fixed-length
characters. strings. Space padded on right to equal size characters.
VARCHAR(size) Maximum size of 255 Where size is the number of characters to store. Variable-
characters. length string.
TEXT(size) Maximum size of Where size is the number of characters to store.
65,535 characters.
BINARY(size) Maximum size of 255 Where size is the number of binary characters to store.
characters. Fixed-length strings. Space padded on right to equal size
characters.
(Introduced in MySQL 4.1.2)

Numeric Datatypes
The following are the Numeric Datatypes in MySQL:

94
Data Type Maximum Size Explanation
Syntax
INTEGER(m) Standard integer value. This is a synonym for the INT datatype.
Signed values range from -
2147483648 to 2147483647.
Unsigned values range from 0 to
4294967295.
DECIMAL(m,d) Unpacked fixed point number. Where m is the total digits and d is the
m defaults to 10, if not specified. number of digits after the decimal.
d defaults to 0, if not specified.
FLOAT(m,d) Single precision floating point Where m is the total digits and d is the
number. number of digits after the decimal.
DOUBLE(m,d) Double precision floating point Where m is the total digits and d is the
number. number of digits after the decimal.
BOOLEAN Synonym for TINYINT(1) Treated as a boolean data type where a value
of 0 is considered to be FALSE and any
other value is considered to be TRUE.

Date/Time Datatypes
The following are the Date/Time Datatypes in MySQL:

Data Type Maximum Size Explanation


Syntax
DATE Values range from '1000-01-01' to '9999-12-31'. Displayed as 'YYYY-MM-
DD'.
DATETIME Values range from '1000-01-01 00:00:00' to '9999- Displayed as 'YYYY-MM-DD
12-31 23:59:59'. HH:MM:SS'.
TIMESTAMP(m) Values range from '1970-01-01 00:00:01' UTC to Displayed as 'YYYY-MM-DD
'2038-01-19 03:14:07' UTC. HH:MM:SS'.

Large Object (LOB) Datatypes


The following are the LOB Datatypes in MySQL:

Data Type Maximum Size Explanation


Syntax
TINYBLOB Maximum size of 255 bytes.
BLOB(size) Maximum size of 65,535 bytes. Where size is the number of characters to store (size
is optional and was introduced in MySQL 4.1)
LONGTEXT Maximum size of 4GB or
4,294,967,295 characters.

MySQL Functions

95
Aggregate functions – provide a brief overview of the most commonly used MySQL aggregate
functions
 AVG – calculate the average value of a set of values or an expression.
 COUNT – count the number rows in a table.
 SUM – calculate the sum of a set of values or an expression.
 CEIL –returns the smallest integer value that is greater than or equal to a number.
 MIN – find the minimum value in a set of values
 MAX – find the maximum value in a set of values
Eg: SELECT MAX(salary) AS "Highest Salary" FROM employees;
 SQRT – returns the square root of a number.
 GREATEST & LEAST – take n arguments and return the greatest and least values of the n
arguments respectively.

String functions
 CONCAT – combine two or more strings into one string.
Syntax: CONCAT( expression1, expression2, ... expression_n )
 LENGTH & CHAR_LENGTH – returns the length of the specified string (measured in
characters).
Syntax: CHAR_LENGTH( string ) OR CHARACTER_LENGTH( string )
 LEFT – get the left part of a string with a specified length ie., allows you to extract a
substring from a string, starting from the left-most character. RIGHT()
Syntax: LEFT( string, number_of_characters )
Eg: SELECT LEFT('Tech on the net', 1); //Returns T
 REPLACE – search and replaces a substring in a string.
Syntax: REPLACE( string, from_substring, to_substring )
Eg: SELECT REPLACE('techonology', ‘techonology’, ' replaced');// replaced
 RPAD(string,length,pad_string) ‘length’ of the result after string has been right-padded. LPAD()
Eg: SELECT RPAD('techonology', 18, 'A');
 REVERSE( string )
 LCASE( string ) string to convert to lowercase. LOWER UPPER UCASE
 SUBSTRING – extract a substring starting from a position with a specific
length.
Syntax: substr(string, start_pos,length)
 TRIM – remove unwanted characters from a string.

96
RTRIM( string ) Trims Spaces on Right LTRIM
 REPEAT( string, number ) number of times to repeat the string.
Eg: SELECT REPEAT('abc', 2); //abcabc
 INSTR( string, substring ) returns the location of a substring in a string. Eg: SELECT
INSTR('Tech on the net', 'T'); //Returns 1
 FIND_IN_SET – find a string within a comma-separated list of strings.
Syntax: FIND_IN_SET( string, string_list )
Eg: SELECT FIND_IN_SET('b', 'a,b,c,d,e,f');
 FORMAT – format a number with a specific locale, rounded to the number of
decimals
Syntax: FORMAT( number, decimal_places )
Eg: SELECT FORMAT(12345.6789, 2); //12345.68
 ASCII - returns the numeric value of the left-most character of a string.
Syntax: ASCII( single_character )
 STRCMP( string1, string2 )
Eg: SELECT STRCMP('techonthenet.com', 'techonthenet.com');

If string1 and string2 are the same, the STRCMP function will return 0.
If string1 is smaller than string2, the STRCMP function will return -1.
If string1 is larger than string2, the STRCMP function will return 1.
 SUBSTRING_INDEX( string, delimiter, number ) returns the substring of string before number
of occurrences of delimiter.
String The source string.
Delimiter The delimiter to search for in string.
Number The number of times to search for delimiter.
Eg: SELECT SUBSTRING_INDEX('www.techonthenet.com', '.', 1);
 SUBSTRING( string, start_position, [ length ] ) SUBSTR

Date and time functions


 CURDATE – return the current date.
 DATEDIFF – calculate the number of days between two DATE values.
DATEDIFF(`changedat`,curdate())
 DAY – get the day of the month of a specified date. DAY(`date column name` OR
‘date’)

97
 DATE_SUB – MySQL DATE_SUB function returns a date after which a certain time/date
interval has been subtracted. Syntax: DATE_ADD( date, INTERVAL value unit )
DAY, HOUR, MINUTE, YEAR, WEEK, MONTH, SECOND, QUATER
SELECT DATE_SUB('2014-02-13', INTERVAL 10 DAY); DATE_ADD
SELECT DATE_ADD(`changedat`, INTERVAL -2 HOUR) FROM `employee_audit`;
 DATE_FORMAT – format a date value based on a specified date format.
Eg: SELECT DATE_FORMAT('2014-02-28', '%Y');

%a Weekday name abbreviated (Sun to Sat)


%W weekday full
%w Numeric (0-6)
%b Month name abbreviated (Jan to Dec)
%c numeric value (0 to 12)
%D Day of the month as a numeric value, followed by suffix (1st, 2nd, 3rd, ...)
%d Day of the month as a numeric value (01 to 31)
%H Hour (00 to 23)
%h Hour (00 to 12)
%i Minutes
%j Day of the year (001 to 366)
%M Month name in full (January to December)
%m Numeric value
%p AM or PM
%T Time in 24 hour format (hh:mm:ss)
%Y Year as a numeric, 4-digit value
%y Year as a numeric, 2-digit value

DAYNAME – name of a weekday for a specified date. Syntax: DAYNAME( date_value )


SELECT DAYNAME('2014-01-27'); Result: 'Monday'
DAYOFWEEK – return the weekday index for a date. SELECT DAYOFWEEK(CURDATE());
 MONTH– return an integer that represents a month of a specified date.
 STR_TO_DATE – convert a string into a date and time value based on a specified format.
Syntax: STR_TO_DATE( string, format_mask )
SELECT STR_TO_DATE('February 01 2014', '%M %d %Y');
 TIMEDIFF – calculate the difference between two TIME or DATETIME values.
 TIMESTAMPDIFF – calculate the difference between two DATE or DATETIME values..
 WEEK – return a week number of a date.
 YEAR – return the year part of a date value.
MySQL comparison functions

98
 GREATEST & LEAST – take n arguments and return the greatest and least values of the n
arguments respectively.
 ISNULL – return 1 if the argument is NULL, otherwise return zero.
Other MySQL functions
 LAST_INSERT_ID – obtain the last generated sequence number of the last inserted record.
 CAST – convert a value of any type into a value with a specified type.

MySQL Operators

 Between and MySQL BETWEEN AND operator checks whether a value is within a range.
Syntax: expr BETWEEN min AND max
If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1,
otherwise, it returns 0. This is equivalent to the expression (min <= expr AND expr <= max) if all the
arguments are of the same type. Otherwise, type conversion takes place according to the rules
1. SELECT pub_name,country,pub_city,estd FROM publisher
WHERE YEAR(estd) BETWEEN 1968 AND 1975;
2. SELECT pub_name,country,pub_city,estd FROM publisher
WHERE MONTH(estd) BETWEEN '02' and '08';

 IN() function finds a match in the given arguments. Syntax: expr IN (value,..)
The function returns 1 if expr is equal to any of the values in the IN list, otherwise, returns 0. Eg:
SELECT 10 IN(15,10,25);
SELECT * FROM `cars` WHERE Price in (1000000, 2000000)
SELECT * FROM `cars` WHERE Model in ('Hundai', 'BMW')
 INTERVAL() MySQL INTERVAL() function returns the index of the argument that is less than
the first argument. It returns 0 if 1st number is less than the 2nd number and 1 if 1st number is
less than the 3rd number and so on or -1 if 1st number is NULL. All arguments are treated as an
integer.
Syntax: INTERVAL(N,N1,N2,N3,...)
The following MySQL statement the 1st number is 85, which is less than 175. All other numbers in the
argument are smaller than 85. So, it returns the index of 175. Notice that indexing is started with the 2nd
number and first position is zero.
Code: SELECT INTERVAL(85, 1, 75, 17, 30,56, 175);

MySQL Comparision Operator


 NULL Safe equal to operator (<=>)
 Equal operator(=)
 Greater than or equal operator(>=)
 Greater than operator(>)

99
 IS NOT NULL
 IS NOT MySQL IS NOT operator will test a value against a boolean value. A boolean
value can be TRUE, FALSE, or UNKNOWN.
Eg: SELECT 2 IS NOT UNKNOWN, 0 IS NOT UNKNOWN, NULL IS NOT UNKNOWN;
 IS NULL MySQL IS NULL operator tests whether a value is NULL. If satisfied, then
returns 1 otherwise returns 0.
Syntax: IS NULL
 SELECT 2 IS NULL, 0 IS NULL, NULL IS NULL;
 IS operator tests a value against a Boolean value. A boolean value can be TRUE, FALSE, or UNKNOWN.
Eg: SELECT 5 IS TRUE, 0 IS TRUE, NULL IS UNKNOWN;
 IS NULL()MySQL ISNULL() function returns 1 when the expression is NULL otherwise
it returns 0.
Syntax: ISNULL(expr)
 Example: In the following MySQL statement, given argument is a non-NULL value. So ,
ISNULL function returns 0.
 Code: SELECT ISNULL(1+0);
 GREATEST()
 LEAST()MySQL LEAST() function returns the smallest argument from two or more arguments.
Syntax: LEAST(value1,value2,...)

The arguments are compared using the following rules:


 If any argument is NULL, the result is NULL. No comparison is needed.
 If the return value is used in an INTEGER context or all arguments are integer-valued,
they are compared as integers.
 If the return value is used in a REAL context or all arguments are real-valued, they are
compared as reals.
 If the arguments comprise a mix of numbers and strings, they are compared as numbers.
 If any argument is a nonbinary (character) string, the arguments are compared as
nonbinary strings.
 In all other cases, the arguments are compared as binary strings.

The following MySQL statement will find the smallest out of the list of arguments.
SELECT LEAST(15,10,25); //Returns 10

 LESS THAN OR EQUAL OPERATOR(<=)


 LESS THAN OPERATOR(<)
 LIKE
 NOT BETWEEN AND
 NOT EQUAL OPERATOR(<>,!=)
 NOT IN()

100
 NOT LIKE

Llogical AND operators

Some Logical Operators are -


 And operator
 Not operator MySQL NOT operator reverses or negates the input. Syntax: NOT, !
The operator returns 1 if the operand is 0 and returns 0 if the operand is nonzero. It returns
NULL if the operand is NOT NULL.
 Or operator
 Xor operator MySQL XOR operator checks two operands (or expressions) and returns
TRUE if one or the other but not both is TRUE. Syntax: XOR
MySQL Logical XOR returns a NULL when one of the operands is NULL. It returns 1 when one
operand is NULL and an odd number of operands are nonzero and returns 0 when no operand is
NULL and even number of operands are nonzero. The actual mathematical representation of a
XOR equation "A XOR B" is "(A AND (NOT B)) OR ((NOT A) AND B)".
In the following MySQL statement, both of the operands are true, so it returns FALSE.
Code: SELECT 1 XOR 1;

SQL statements
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data. Most of the actions you need
to perform on a database are done with SQL statements. Structured Query Language(SQL) as we
all know is the database language by the use of which we can perform certain operations on the
existing database and also we can use this language to create a database. SQL uses certain
commands like Create, Drop, Insert etc. to carry out the required tasks.

SQL keywords are NOT case sensitive: select is the same as SELECT. Some database systems
require a semicolon at the end of each SQL statement. Semicolon is the standard way to separate
each SQL statement in database systems that allow more than one SQL statement to be executed
in the same call to the server.

These SQL statements are mainly categorized into four categories as discussed below:

1. DDL(Data Definition Language) : DDL or Data Definition Language actually consists


of the SQL commands that can be used to define the database schema. It simply deals
with descriptions of the database schema and is used to create and modify the structure of
database objects in database.

Examples of DDL commands:

101
 CREATE – is used to create the database or its objects (like table, index, function, views, store
procedure and triggers).
 DROP – is used to delete objects from the database.
 ALTER-is used to alter the structure of the database.
 TRUNCATE–is used to remove all records from a table, including all spaces allocated for the
records are removed.
 COMMENT –is used to add comments to the data dictionary.
 RENAME –is used to rename an object existing in the database.
2. DML (Data Manipulation Language) : The SQL commands that deals with the manipulation of data
present in database belong to DML or Data Manipulation Language and this includes most of the SQL
statements.

Examples of DML:

 SELECT – is used to retrieve data from the database.


 INSERT – is used to insert data into a table.
 UPDATE – is used to update existing data within a table.
 DELETE – is used to delete records from a database table.

3. DCL (Data Control Language) : DCL includes commands such as GRANT and REVOKE which
mainly deals with the rights, permissions and other controls of the database system.

Examples of DCL commands:

 GRANT-gives user’s access privileges to database.


 REVOKE-withdraw user’s access privileges given by using the GRANT command.

4. TCL(transaction Control Language) : TCL commands deals with the transaction within the
database.

Examples of TCL commands:

 COMMIT– commits a Transaction.


 ROLLBACK– rollbacks a transaction in case of any error occurs.
 SAVEPOINT–sets a savepoint within a transaction.
 SET TRANSACTION–specify characteristics for the transaction.

MySQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

Syntax
CREATE DATABASE databasename;

Eg: CREATE DATABASE testDB;

102
MySQL ALTER DATABASE
The ALTER DATABASE statement is used to modify, maintain, or recover an existing database.

ALTER {DATABASE | SCHEMA} [db_name]


alter_specification ...

alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name

Eg: ALTER DATABASE test CHARACTER SET = 'utf8' | COLLATE = 'utf8_bin';

To rename the mysql database, you need to follow the following syntax:

1. RENAME DATABASE old_db_name TO new_db_name;

MySQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.

Syntax
DROP DATABASE databasename;

Eg: DROP DATABASE testDB;

MySQL CREATE TABLE Statement

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

Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype, ....
);

The column parameters specify the names of the columns of the table. The datatype parameter
specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).

Eg: CREATE TABLE Customers (


CustomerID int(10),
CustomerName varchar(255),
Address varchar(255),
City varchar(255) ,
Country varchar(255),
PostalCode varchar(255),
);

103
MySQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

This statement is also used to add and drop various constraints on an existing table.

ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name ADD column_name datatype;

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):

ALTER TABLE table_name DROP COLUMN column_name;

ALTER TABLE - ALTER/MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

MySQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.

Syntax
DROP TABLE table_name;

Example

DROP TABLE Customers;

MySQL TRUNCATE TABLE

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.

Syntax
TRUNCATE TABLE table_name;

Example

104
TRUNCATE TABLE Customers;

MySQL RENAME Statement

With RENAME statement you can rename a table.

Some of the relational database management system (RDBMS) does not support this command,
because this is not standardizing statement.

For example renaming a table through MS SQL Server you must use storage procedure
SP_RENAME.

Syntax for MySQL RENAME is:


RENAME TABLE {tbl_name} TO {new_tbl_name};

Where {tbl_name} table that exists in the current database, and {new_tbl_name} is new
table name.

UNIT - 4

MySQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

DELETE Example

105
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

CustomerID CustomerName Address City PostalCode Country


2 Ana Trujillo Avda. de la México 05021 Mexico
Emparedados y Constitución 2222 D.F.
helados
3 Antonio Moreno Mataderos 2312 México 05023 Mexico
Taquería D.F.
4 Around the Horn 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden

Delete All Records

It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

DELETE FROM table_name;


or:
DELETE * FROM table_name;

To add a new AUTO_INCREMENT integer column named CustomerID:

ALTER TABLE Customers ADD CustomerID INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (CustomerID);

We indexed c (as a PRIMARY KEY) because AUTO_INCREMENT columns must be indexed, and we
declare c as NOT NULL because primary key columns cannot be NULL. When you add an
AUTO_INCREMENT column, column values are filled in with sequence numbers automatically.

MySQL INSERT Statement


To insert data into a MySQL table, you would need to use the SQL INSERT INTO command.
You can insert data into the MySQL table by using the mysql> prompt or by using any script like
PHP.

Syntax of INSERT INTO command to insert data into the MySQL table −
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );

106
To insert string data types, it is required to keep all the values into double or single quotes. For
example "value".

Inserting Data from the Command Prompt


To insert data from the command prompt, we will use SQL INSERT INTO command to insert
data into MySQL table tutorials_tbl.

Example

The following example will create 3 records into Customers table –

root@host# mysql -u root -p password;


Enter password:*******
mysql> use TUTORIALS;
Database changed

mysql> INSERT INTO Customers


->(CustomerName, Address, City, Country, PostalCode)
->VALUES
->("John Poul", "Horamavu", "Bangalore", "INDIA", "560043");
Query OK, 1 row affected (0.01 sec)

mysql>

NOTE − Please note that all the arrow signs (->) are not a part of the SQL command. They are
indicating a new line and they are created automatically by the MySQL prompt while pressing
the enter key without giving a semicolon at the end of each line of the command.

In the above example, we have not provided a CustomerID because at the time of table creation,
we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting
these IDs automatically.

DO Statement

Syntax DO expr [, expr] ...

DO executes the expressions but does not return any results. In most respects, DO is shorthand for
SELECT expr, ..., but has the advantage that it is slightly faster when you do not care about the
result.

DO is useful primarily with functions that have side effects, such as RELEASE_LOCK().

Example: This SELECT statement pauses, but also produces a result set:

mysql> SELECT SLEEP(5);


+----------+
| SLEEP(5) |

107
+----------+
| 0|
+----------+
1 row in set (5.02 sec)

DO, on the other hand, pauses without producing a result set.:

mysql> DO SLEEP(5);
Query OK, 0 rows affected (4.99 sec)

REPLACE Statement

REPLACE INTO table_name(column_list) VALUES(value_list);

REPLACE is a MySQL extension to the SQL standard. REPLACE works exactly like INSERT,
except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a
UNIQUE index, the old row is deleted before the new row is inserted. Values for all columns are
taken from the values specified in the REPLACE statement. Any missing columns are set to their
default values, just as happens for INSERT. You cannot refer to values from the current row and
use them in the new row.

To use REPLACE, you must have both the INSERT and DELETE privileges for the table.

The REPLACE statement returns a count to indicate the number of rows affected. This is the sum
of the rows deleted and inserted. If the count is 1 for a single-row REPLACE, a row was inserted
and no rows were deleted. If the count is greater than 1, one or more old rows were deleted
before the new row was inserted. It is possible for a single row to replace more than one old row
if the table contains multiple unique indexes and the new row duplicates values for different old
rows in different unique indexes.

For Example, CREATE TABLE cities (id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(50), population INT NOT NULL);

INSERT INTO cities(name,population) VALUES ('New York',8008278),


('Los Angeles',3694825), ('San Diego',1223405);

Now,

REPLACE INTO cities(id,population) VALUES(2,3696820); //name column is NULL now.

However, the REPLACE statement does not behave this way. In this case, the REPLACE statement
works as follows:

108
1. The REPLACE statement first inserts the new row into the cities table with the information
provided by the column list. The insertion fails because the row with id 2 already exists
in the cities table, therefore, MySQL raises a duplicate-key error.
2. The REPLACE statement then updates the row that has the key specified in the value of the
id column. In the normal process, it would delete the old row with conflict id first and
then inserts a new row

SQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.

Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

 You can update one or more field altogether.


 You can specify any condition using the WHERE clause.
 You can update the values in a single table at a time.

The WHERE clause is very useful when you want to update the selected rows in a table.

Eg: UPDATE Customers


SET CustomerName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

SELECT Statement

The SQL SELECT command is used to fetch data from the MySQL database. . You can use this
command at mysql> prompt as well as in any script like PHP.

Syntax syntax of SELECT command to fetch data from the MySQL table −
SELECT field1, field2,...fieldN
FROM table_name1, table_name2...
[WHERE Clause]
[OFFSET M ][LIMIT N]
 You can use one or more tables separated by comma to include various conditions using
a WHERE clause, but the WHERE clause is an optional part of the SELECT command.
 You can fetch one or more fields in a single SELECT command.
 You can specify star (*) in place of fields. In this case, SELECT will return all the fields.
 You can specify any condition using the WHERE clause.
 You can specify an offset using OFFSET from where SELECT will start returning
records. By default, the offset starts at zero.

109
 You can limit the number of returns using the LIMIT attribute.

Example:

SELECT * from cities;


SELECT name from cities WHERE id>1 LIMIT 10;

MySQL Subqueries

A subquery is a SQL query nested inside a larger query.


 A subquery may occur in:
o A SELECT clause
o A FROM clause
o A WHERE clause
 In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE,
SET, or DO statement or inside another subquery.
 A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
 You can use the comparison operators, such as >, <, or =. The comparison operator can
also be a multiple-row operator, such as IN, ANY, SOME, or ALL.
 A subquery can be treated as an inner query, which is a SQL query placed as a part of
another query called as outer query.
 The inner query executes first before its parent query so that the results of the inner query
can be passed to the outer query.
Syntax:

SELECT select_list FROM table WHERE expr operator


(SELECT select_list FROM table);

MySQL Subqueries in the FROM Clause

Subqueries work in a SELECT statement's FROM clause. The syntax is :

SELECT ... FROM (subquery) [AS] name ...

Every table in a FROM clause must have a name, therefore the [AS] name clause is mandatory.
Any columns in the subquery select list must have unique names.

Example: MySQL Subqueries in the FROM Clause

We have the following table tb1.

mysql> CREATE TABLE tb1 (c1 INT, c2 CHAR(5), c3 FLOAT); Query OK, 0 rows affected (0.73 sec)

Let insert some values into tb1.

INSERT INTO tb1 VALUES (1, '1', 1.0),(2, '2', 2.0), (3, '3', 3.0);

110
Query OK, 3 row affected (0.03 sec)

mysql> select * from tb1;


+------+------+------+
| c1 | c2 | c3 |
+------+------+------+
| 1|1 | 1|
| 2|2 | 2|
| 3|3 | 3|
+------+------+------+
3 rows in set (0.00 sec)

Here is how to use a subquery in the FROM clause, using the example table (tb1):

mysql> SELECT sc1, sc2, sc3


FROM (SELECT c1 AS sc1, c2 AS sc2, c3*3 AS sc3 FROM tb1) AS sb
WHERE sc1 > 1;
+------+------+------+
| sc1 | sc2 | sc3 |
+------+------+------+
| 2|2 | 6|
| 3|3 | 9|
+------+------+------+
2 rows in set (0.02 sec)

EMPLO FIRST_ LAST_ EMAI PHONE_N HIRE_ JOB_I SAL MANA DEPART
YEE_ID NAME NAME L UMBER DATE D ARY GER_ID MENT_ID
100 Steven King SKING 515123456 17-Jun- AD_PR 2400 90
7 87 ES 0
101 Neena Kochhar NKOC 515123456 21-Sep- AD_VP 1700 100 90
HHAR 8 89 0
102 Lex De LDEH 515123456 13-Jan- AD_VP 1700 100 90
Haan AAN 9 93 0
103 Alexand Hunold AHUN 590423456 3-Jan- IT_PRO 9000 102 60
er OLD 7 90 G
104 Bruce Ernst BERN 590423456 21- IT_PRO 6000 103 60
ST 8 May-91 G
105 David Austin DAUS 590423456 25-Jun- IT_PRO 4800 103 60
TIN 9 97 G
106 Valli Pataball VPAT 590423456 5-Feb- IT_PRO 4800 103 60
a ABAL 0 98 G
107 Diana Lorentz DLOR 590423556 7-Feb- IT_PRO 4200 103 60
ENTZ 7 99 G
108 Nancy Greenbe NGRE 515124456 17- FI_MG 1200 101 100
rg ENBE 9 Aug-94 R 0
109 Daniel Faviet DFAVI 515124416 16- FI_ACC 9000 108 100
ET 9 Aug-94 OUNT
110 John Chen JCHEN 515124426 28-Sep- FI_ACC 8200 108 100
9 97 OUNT

Example:
Using a subquery, list the name of the employees, paid more than 'Alexander' from emp_details.

111
SELECT first_name,last_name, salary FROM emp_details
WHERE salary >(SELECT salary FROM emp_details
WHERE first_name='Alexander');

Subqueries: Guidelines

There are some guidelines to consider when using subqueries :


- A subquery must be enclosed in parentheses.
- Use single-row operators with single-row subqueries, and use multiple-row operators with
multiple-row subqueries.
- If a subquery (inner query) returns a null value to the outer query, the outer query will not
return any rows when using certain comparison operators in a WHERE clause.

MySQL Subqueries in the SELECT Clause

SELECT first_name, (SELECT MAX(SALARY) FROM emp_details

Stored routines

MySQL supports stored routines (procedures and functions). A stored routine is a set of SQL
statements that can be stored in the server. Once this has been done, clients don't need to keep
reissuing the individual statements but can refer to the stored routine instead. A stored routine is
either a procedure or a function.

MYSQL Function

stored function is a special kind stored program that returns a single value. You use stored
functions to encapsulate common formulas or business rules that are reusable among SQL
statements or stored programs. It must return value. IN, OUT and INOUT cannot be used in
function. But return datatype must be declare when create a function. function can be called from
a SQL statement. Function return one values.

CREATE FUNCTION hello (s CHAR(20))


RETURNS CHAR(50) DETERMINISTIC
RETURN CONCAT('Hello, ',s,'!')
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT hello('world');

DELIMITER $$

CREATE FUNCTION CustomerLevel(creditLimit double) RETURNS VARCHAR(10)


DETERMINISTIC
BEGIN
DECLARE lvl varchar(10);

112
IF creditLimit > 50000 THEN
SET lvl = 'PLATINUM';
ELSEIF (creditLimit <= 50000 AND creditLimit >= 10000) THEN
SET lvl = 'GOLD';
ELSEIF creditLimit < 10000 THEN
SET lvl = 'SILVER';
END IF;
RETURN (lvl);
END

Function CALL

SELECT customerName, CustomerLevel(creditLimit)


FROM customers ORDER BY customerName;

MYSQL Procedure

A procedure (often called a stored procedure) is a subroutine like a subprogram in a regular


computing language, stored in database. A procedure has a name, a parameter list, and SQL
statement(s). All most all relational database system supports stored procedure.

DELIMITER //
CREATE PROCEDURE country_hos
(IN con CHAR(20))
BEGIN
SELECT Name, HeadOfState FROM Country
WHERE Continent = con;
END //
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE GetCustomerLevel(
IN customerNumber INT(11),
OUT customerLevel varchar(10)
)
BEGIN
DECLARE creditlim DOUBLE;

SELECT creditlimit INTO creditlim


FROM customers
WHERE customerNumber = customerNumber;

SELECT CUSTOMERLEVEL(creditlim)
INTO customerLevel;

END
113
CREATE PROCEDURE GetCustomers()
BEGIN
SELECT CustomerName, creditlimit FROM customers;
END

Difference between function and procedures.

1. A FUNCTION always returns a value using the return statement. PROCEDURE may
return one or more values through parameters or may not return any at all.
2. Functions are normally used for computations where as procedures are normally used for
executing business logic.
3. A Function returns 1 value only. Procedure can return multiple values (max 1024).
4. Stored procedure always returns an integer value of zero by default. Whereas function
return types could be scalar or table or table values.
5. Stored procedures have a precompiled execution plan, where as functions are not.
6. A function can be called directly by SQL statement like select func_name from dual
while procedures cannot.
7. Stored procedure has the security and reduces the network traffic and also we can call
stored procedure in any no. of applications at a time.
8. A Function can be used in the SQL Queries while a procedure cannot be used in SQL
queries .that cause a major difference b/w function and procedures.

TRIGGERS
MySQL trigger is a database object that is associated with a table. It will be activated when a
defined action is executed for the table. The trigger can be executed when you run one of the
following MySQL statements on the table: INSERT, UPDATE and DELETE and it can be
invoked before or after the event.

Syntax

CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name FOR EACH ROW
[trigger_order]
trigger_body

trigger_time: { BEFORE | AFTER } is the trigger action time. It can be BEFORE or AFTER to
indicate that the trigger activates before or after each row to be modified.
trigger_event: { INSERT | UPDATE | DELETE } indicates the kind of operation that activates the
trigger. These trigger_event values are permitted: INSERT | UPDATE | DELETE

114
trigger_order: { FOLLOWS | PRECEDES } other_trigger_name

The DEFINER clause determines the security context to be used when checking access privileges at
trigger activation time.

EXAMPLE

First, create a new table named employees_audit to keep the changes of the employee table. The
following statement creates the employee_audit table.

CREATE TABLE employees_audit (


id INT AUTO_INCREMENT PRIMARY KEY,
employeeNumber INT NOT NULL,
lastname VARCHAR(50) NOT NULL,
changedat DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL
);

Next, create a BEFORE UPDATE trigger that is invoked before a change is made to the employees
table.

DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;

Inside the body of the trigger, we used the OLD keyword to access employeeNumber and lastname
column of the row affected by the trigger.

Notice that in a trigger defined for INSERT, you can use NEW keyword only. You cannot use the
OLD keyword. However, in the trigger defined for DELETE, there is no new row so you can use
the OLD keyword only. In the UPDATE trigger, OLD refers to the row before it is updated and
NEW refers to the row after it is updated.

Then, to view all triggers in the current database, you use SHOW TRIGGERS statement

Realtime Example: Triggers are used to store old passwords into NEW table (netbanking
websites) whenever they are updated by USER

115
Uses of Triggers

A database trigger is special stored procedure that is run when specific actions occur within a
database. Most triggers are defined to run when changes are made to a table's data. Triggers can
be defined to run instead of or after DML (Data Manipulation Language) actions such as
INSERT, UPDATE, and DELETE.

LAST_INSERT_ID() function returns the first AUTO_INCREMENT value that was set by
the most recent INSERT or UPDATE statement. The value of LAST_INSERT_ID() remains
unchanged if no rows are successfully inserted.

Syntax

LAST_INSERT_ID(expression) where expression is optional

The ID that was generated is maintained in the server on a per-connection basis. This means that
the value returned by the function to a given client is the first AUTO_INCREMENT value generated
for most recent statement affecting an AUTO_INCREMENT column by that client. This value
cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own.
This behavior ensures that each client can retrieve its own ID without concern for the activity of
other clients, and without the need for locks or transactions.

View

View can be described as virtual table which derived its data from one or more than one table
columns. It is stored in the database. View can be created using tables of same database or
different database. They do not contain the data that is returned. The data is stored in the tables
referenced in the SELECT statement.

Views improve security of the database by showing only intended data to authorized users. They
hide sensitive data.
For example:

Create table Emp_Details(EmpId int, EmpName nvarchar(200),


EmpLogin nvarchar(20), EmpPassword nvarchar(20) , EmploymentDate datetime )

And for example, table has the following data of employees:

EmpId EmpName EmpLogin Emppassword EmploymentDate


1 EmployeeA EmpA EmpAPwd 29/01/2006
2 EmployeeB EmpB EmpBPwd 06/02/2007
3 EmployeeC EmpC EmpCPwd 14/05/2007
4 EmployeeD EmpD Empd 30/03/2008
5 EmployeeE EmpE EmpEPwd 30/06/2007

116
6 EmployeeF EmpF EmpFPwd 12/09/2012

Now suppose that the Administrator do not want that the users to access the whole data of
Emp_Details table which contains some critical information (Emplogin, EmpPassword, etc.) of the
Employees. So he can create a view which gives the empid, empname, employmentdate as the output
and gives permission for the view to the user. In this way, the administrator does not need to give
access permission for the table to the user.

Use of a View

You may want to use views primarily for following 3 reasons

 Ultimately , you will use your SQL knowledge , to create applications , which will use a
database for data requirements. It's recommended that you use VIEWS of the original
table structure in your application instead of using the tables themselves. This ensures
that when you make changes to your database structure, your applications will not break.
 VIEWS increase re-usability. You will not have to create complex queries involving joins
repeatedly. All the complexity is converted into a single line of query use VIEWS. Such
condensed code will be easier to integrate in your application. This will eliminates
chances of typos and your code will be more readable.
 VIEWS help in data security. You can use views to show only authorized information to
users and hide sensitive data like credit card numbers.

The syntax for creating a View is given below:

Create View Viewname As


Select Column1, Column2 From Tablename
Where (Condition) Group by (Grouping Condition) having (having Condition)

For example:
Create View View_Employeeinfo As s
Select EmpId, EmpName, employmentdate From EmployeeInfo
Now user can use the view "View_EmployeeInfo" as a table to get the empid, empname and
employmentdate information
of the employees by using the following query:

Select * from View_EmployeeInfo where empid=3

It would give the following result:

EmpId EmpName EmploymentDate


3 EmployeeC 14/05/2007

Altering an View

If we want to alter the view, then we can use the Alter View command to alter the view. For
example,
Alter view Vw_EmployeeProj As

117
Select Emp_Details.EmpId, Emp_Details.EmpName,
EmpProjInfo.Projectname from Emp_Details inner join
EmpProjInfo on Emp_Details.EmpId=EmpProjInfo.EmpId where Emp_Details.EmpId in (2,3,4)

Dropping a View

We can use the Drop command to drop a view. For example, to drop the view Vw_EmployeeInfo,
we can use the following statement:

Eg: Drop view Vw_EmployeeInfo

View vs Table

A view is a virtual table or is like a macro or alias to an underlying query. A view consists of
rows and columns just like a table. The difference between a view and a table is that views are
definitions built on top of other tables (or views), and do not hold data themselves. If data is
changing in the underlying table, the same change is reflected in the view.

You can insert a small subset of rows from the source tables into your temporary table, but a
view will always read the table with the full set of rows.

GRANT and REVOKE

With these commands, users can be both created and disabled, and their access privileges can be
both granted and revoked using a much more intuitive and foolproof syntax. Their exacting
syntax eliminates potentially horrendous mistakes that could otherwise be introduced due to a
malformed SQL query

CREATE USER user [IDENTIFIED BY [PASSWORD] 'password']


[, user [IDENTIFIED BY [PASSWORD] 'password']] ...

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

Granting Privileges

GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';

GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

Creating a New User and Assigning Initial Privileges

mysql>GRANT SELECT, INSERT ON books.* TO 'michele'@'192.168.1.103'


->IDENTIFIED BY 'secret';

Granting Table-Level Privileges

118
mysql>GRANT DELETE ON books.authors TO 'michele'@'192.168.1.103';

Granting Column-Level Privileges

mysql>GRANT UPDATE (name) ON books.authors TO 'nino'@'192.168.1.105';

Granting Multiple Table-Level Privileges

mysql>GRANT SELECT,INSERT,DELETE ON
->books.authors TO 'rita'@'%.wjgilmore.com'
->IDENTIFIED BY 'secret';

Revoking Privileges

REVOKE privilege_type [(column_list)] [, privilege_type [(column_list)] ...]


ON {table_name | * | *.* | database_name.*}
FROM user_name [, user_name ...]

mysql>REVOKE ALL privileges ON books.* FROM 'rita'@'192.168.1.102';


mysql>REVOKE INSERT (name) ON books.authors FROM 'rita'@'192.168.1.102';
mysql>REVOKE INSERT ON books.* FROM 'rita'@'192.168.1.102';
mysql>REVOKE INSERT, UPDATE ON books.authors FROM 'rita'@'192.168.1.102';

DROP USER ‘demo’@‘localhost’;

GRANT and REVOKE Tips


The following list offers various tips to keep in mind when you’re working with GRANT and
REVOKE:
 You can grant privileges for a database that doesn’t yet exist.
 If the user identified by the GRANT command does not exist, it will be created.
 If you create a user without including the IDENTIFIED BY clause, no password will
be required for login.
 If an existing user is granted new privileges, and the GRANT command is
accompanied by an IDENTIFIED BY clause, the user’s old password will be replaced
with the new one.
 Table-level GRANTs only support the following privilege types: ALTER, CREATE,
CREATE

119
VIEW, DELETE, DROP, GRANT, INDEX, INSERT, REFERENCES, SELECT, SHOW
VIEW, and UPDATE.
 Column-level GRANTs only support the following privilege types: INSERT, SELECT,
and UPDATE.

Reviewing Privileges

mysql>SHOW GRANTS FOR CURRENT_USER();


mysql>SHOW GRANTS FOR 'rita'@'192.168.1.102';

Limiting User Resources

Monitoring resource usage is always a good idea, but it is particularly important when you’re
offering MySQL in a hosted environment, such as an ISP. If you’re concerned with such a
matter, you will be happy to learn that, as of version 4.0.2, it’s possible to limit the consumption
of MySQL resources on a per-user basis. These limitations are managed like any other privilege,
via the privilege tables. In total, four privileges concerning the use of resources exist, all of
which are located in the user table:

 max_connections: Determines the maximum number of times the user can


connect to the database per hour
 max_questions: Determines the maximum number of queries (using the SELECT
command) that the user can execute per hour
 max_updates: Determines the maximum number of updates (using the INSERT and
UPDATE commands) that the user can execute per hour
 max_user_connections: Determines the maximum number of simultaneous
connections a given user can maintain (added in version 5.0.3)
Consider a couple examples. The first limits user dario@%.wjgilmore.com‘s number of
connections per hour to 3,600, or an average of one per second:

mysql>GRANT INSERT, SELECT, UPDATE ON books.* TO


->'dario'@'%.wjgilmore.com' IDENTIFIED BY 'secret'
->WITH max_connections_per_hour 3600;

120
List of PHP LAB Programs (BCA 5th Semester)
1. Write a PHP program for Displaying Personal Details (Populating Form)?
2. A. Write a program on sending mail using PHP mailing Function?
B. Write a program on illustrating Constructor and Destructor in PHP?
3. Write a Menu Driven PHP Program to Insert / Remove / Search / Sort / Picking Random element
from Single dimensional Array using SWITCH CASE?
4. Write a Menu Driven PHP Program for different operations on Multi Dimensional Array?
5. Write a PHP program to calculate area of different Shapes implementing Overloading
functionality in PHP?
6. Write a Program illustrating Object Cloning functionality in PHP?
7. Write a PHP program on different File Operations – creation, read, write and Displaying file
contents?
8. Write a PHP program using String Functions, User provided Text?
9. Write a PHP Program to validate Email and Domain Name (Matching Patterns)?
10. Write a PHP program to Upload an Image?
11. Write a PHP program on Session Management (Login Functionality)?
12. Write a PHP program to INSERT user details into MySQL database?
13. Write a PHP program to UPDATE user details on MySQL database?
14. Write a PHP program for RETRIEVING Guest Information using MySQL Stored Procedures?
15. Write a PHP program for Deleting User Information and keeping track of deleted records using
MySQL Triggers?

121
LAB PROGRAM - 1
1. Write a PHP program for Displaying Personal Details (Populating Form)?

1_form.html
<html>
<head>
<title>Process the HTML form data with the POST method</title>
</head>
<style>
.box {
width:400px;
height:250px;
background-color:#90EE90;
position:fixed;
margin-left:-150px; /* half of width */
margin-top:-150px; /* half of height */
top:50%;
left:50%;
padding-left: 15px;
}</style>
<body>

<form name="myform" action="process.php" method="POST">

<table border="0" class="box">


<th><td colspan="2" align="center"><u><b>Personal Details</u></b></td></th>
<tr><td>Name: </td><td><input type="text" name="Name" /></td></tr>
<tr><td>Email: </td><td><input type="text" name="email" maxlength="100" /></td></tr>
<tr><td>Select Season: </td><td>
<select name="Seasons">
<option value="" selected="selected">Select Season</option>
<option value="Spring">Spring</option>
<option value="Summer">Summer</option>
<option value="Autumn">Autumn</option>
<option value="Winter">Winter</option>
</select></td></tr>
<tr><td>Choose one: </td><td>
<input type="radio" name="Country" value="USA" /> USA
<input type="radio" name="Country" value="Canada" /> Canada
<input type="radio" name="Country" value="Other"/> Other
</td></tr>
<tr><td>Choose colors: </td><td>
<input type="checkbox" name="Colors[]" value="green" /> Green
<input type="checkbox" name="Colors[]" value="yellow" /> Yellow

122
<input type="checkbox" name="Colors[]" value="red" /> Red
<input type="checkbox" name="Colors[]" value="gray" /> Gray
</td></tr>
<tr><td colspan="2" align="center"><input type="submit" name="submit" value="submit"
/></td></tr>
</form>
</body>
</html>

process.php
<html>
<head>
<style>
.box {
width:300px;
height:200px;
background-color:#90EE90;
position:fixed;
margin-left:-150px; /* half of width */
margin-top:-150px; /* half of height */
top:50%;
left:50%;
padding-left: 15px;
}</style>
</head>
<body>
<div class="box">
<?php //print_r($_POST);
if (array_key_exists('submit', $_POST)) {
//Check whether a $_GET['Languages'] is set
if ( isset($_POST['Colors']) ) {
$_POST['Colors'] = implode(', ', $_POST['Colors']);
//Converts an array into a single string
}
//Let's now print out the received values in the browser
echo "<br />Your name: {$_POST['Name']}<br />";
echo "Your Email: {$_POST['email']}<br />";
echo "Your favourite season: {$_POST['Seasons']}
<br/><br />";
echo "You are from: {$_POST['Country']}<br />";
echo "Colors you chose: {$_POST['Colors']}<br />";
}
else {

123
echo "You can't see this page without submitting the form.";
}
?>
</div>
</body>
</html>

LAB PROGRAM - 2A

2. A. Write a program on sending mail using PHP mailing Function?

2A_simpleMail.php

<?php
$to = 'pavani@cavalier.com';
$subject = 'Examination TimeTable';
$from = 'admin@cavalier.com';

// 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;">Your Examination will be in August</p>';
$message .= '</body></html>';

// Sending email
if(mail($to, $subject, $message, $headers)){

124
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Note: To send mail to “C:\xampp\mailoutput\” folder, Uncomment below line in “php.ini” file &
restart XAMPP
sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"

OUTPUT:

Your mail has been sent successfully.

LAB PROGRAM – 2B
2. B. Write a program on illustrating Constructor and Destructor in PHP?

2B_ConstDest.php

<?php
class numbers
{
public $a, $b;

public function __construct($a, $b)


{
echo "I am in Constructor";
$this->a = $a;
$this->b = $b;
}

public function Add()


{
$sum = $this->a + $this->b;
return $sum;
}

public function __destruct()


{
print("<br>In Destructor");
unset($this->a);
unset($this->b);
print "<br>Destroyed values";
//echo "<b>Values After Destroying".$this->a;
}
}
$obj = new numbers(10, 20);

125
$sum = $obj->Add();
echo "<br>Sum of 10 and 20 is: ".$sum;
?>

OUTPUT:
I am in Constructor
Sum of 10 and 20 is: 30
In Destructor
Destroyed values

LAB PROGRAM – 3

3. Write a Menu Driven PHP Program to Insert / Remove / Search / Sort / Picking Random element
from Single dimensional Array using SWITCH CASE?

3_switchCase_js.php
<?php
if(!isset($_REQUEST["stack_str"]))
$stack = array(70,20,30);
else
$stack = @explode(",", $_REQUEST["stack_str"]);

@extract($_REQUEST);
$stack_str = @implode(",", $stack);
?>
<!DOCTYPE html>
<html>
<head>
<title>Program to do Operations on Single Dimensional Array using Switch Case</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript">
function validateForm(form) {

if ((document.getElementById("oper_add").checked == false) &&


(document.getElementById("oper_rem").checked == false)&&
(document.getElementById("oper_search").checked == false) &&
(document.getElementById("oper_sort").checked == false ) && (
document.getElementById("oper_rand").checked == false ) )
{
alert("Please select an option");
document.getElementById("oper_add").focus();
return false;
}
if (document.getElementById("oper_add").checked==true &&
document.getElementById("ele_add").value=='') {

126
alert("Please enter number to add");
document.getElementById("ele_add").focus();
return false;
}
if (document.getElementById("oper_search").checked==true &&
document.getElementById("ele_search").value=='') {
alert("Please enter number to search");
document.getElementById("ele_search").focus();
return false;
}
}
</script>
</head>
<body>
<form method="post" name="form1" onsubmit="return validateForm(this.form)">
<table class="box" border="1px" align="center">
<tr><th colspan="2">Operations on Single Dimensional Array</th></tr>
<tr>
<td colspan="2" align="center">
<?php
if(isset($_POST['oper']) && $_POST['oper']!='')
{
extract($_POST);
$st = $_POST['oper'];
switch($st)
{
case "add": array_push($stack,$_POST['ele_add']);
$stack_str = @implode(",", $stack);
print("Element Added Successfully");
break;
case "rem": array_pop($stack);
$stack_str = @implode(",", $stack);
print("Element Added Successfully");
break;
case "search":
if(in_array($ele_search, $stack))
print("Element Found in ");
else
print("Element NOT Found in ");
break;
case "sort": sort($stack);
break;
case "rand": echo 'Random value: '.$stack[array_rand($stack)];
break;

127
}
echo '<br>';
print_r($stack);?></td>
</tr>
<?php } ?>
<tr><td height="40"><input type="radio" name="oper" id="oper_add"
value="add" />Add an Element</td><td><input type="text" name="ele_add" id="ele_add"
/></td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper_rem" value="rem"
/>Remove Element</td><td>&nbsp;</td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper_search" value="search"
/>Search</td><td><input type="text" name="ele_search" id="ele_search" /></td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper_sort" value="sort"
/>Sorting Array</td><td>&nbsp;</td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper_rand" value="rand"
/>Pick a Random value from Array</td><td>&nbsp;</td></tr>
<input type="hidden" name="stack_str" value="<?php print($stack_str);?>">
<tr><td colspan="2" align="center" height="40"><input type="submit"
value="submit"></td></tr>
</table>
</form>
</body>
</html>
style.css
@charset "utf-8";
.box
{
width:500px;
height:500px;
background-color:#d9d9d9;
position:fixed;
}

128
LAB PROGRAM – 4

4.Write a Menu Driven PHP Program for different operations on Multi Dimensional Array?

4_multiDimensionalArray.php

<?php
$stack = array(
"student1" => array(
"Maths" => 50,
"Physics" => 60,
"Chemistry" => 70),
"student2" => array(
"Maths" => 60,
"Physics" => 70,
"Chemistry" => 80),
"student3" => array(
"Maths" => 70,
"Physics" => 80,
"Chemistry" => 90)
);
?>
<!DOCTYPE html>
<html>
<head>

129
<title>Program to do Operations on Multi Dimensional Array</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body> <form method="post" name="form1">
<table class="box" border="1px" align="center">
<tr><th colspan="2">Operations on Multi Dimensional Array</th></tr>
<tr> <td colspan="2">
<?php
echo '<br>Multi Dimensional Array on Student Marks<pre>';
print_r($stack);
echo '</pre>';
?>
</td></tr><tr>
<td> <table>
<tr><td height="40"><input type="radio" name="oper" id="oper" value="show" />Show List of
Students</td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper" value="add" />Add Total
Marks of each Student</td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper" value="display" />Display
Chemistry Marks</td></tr>
<tr><td colspan="2" align="center" height="40"><input type="submit"
value="submit"></td></tr>
</table> </td>
<?php if(isset($_POST['oper']) && $_POST['oper']!='') { ?>
<td><b><u>OUTPUT:<br><br></u></b>
<?php extract($_POST);
$st = $_POST['oper'];
switch($st)
{
case "show":
echo "<br> <b>List of Students</b>";
foreach($stack as $name=>$marks) {
echo "<br>".$name;
}
break;
case "add":
echo "<br> <b>Total Marks</b>";
foreach($stack as $name=>$marks) {
$total = 0;
foreach($marks as $subj=>$mark) {
$total = $total + $mark;
}
echo "<br>".$name." : ".$total;
}

130
break;
case "display":
echo "<br> <b>Chemistry Marks</b>";
foreach($stack as $name=>$marks) {
foreach($marks as $subj=>$mark)
{
if($subj == "Chemistry")
echo "<br>".$name." : ".$mark;
}
}
break;
} ?>
</td>
<?php }?>
</tr></table>
</form>
</body>
</html>

131
LAB PROGRAM - 5

5. Write a PHP program to calculate area of different Shapes implementing Overloading functionality in
PHP?

5_OverLoading.php

<?php
echo '<br>Overloading in PHP (Property/Member and Method)<br><br>';

class Shape
{
const PI = 3.142 ;
private $shape;
public $a, $b;

// Property OR member Overloading (invoked only for assigning value to private members)
public function __set($name, $value)
{
echo "<br><br>Setting '$name' to '$value'\n";
$this->shape = $value;
}
// Property OR member Overloading (invoked only while printing value of private
members)
public function __get($name)
{
echo "<br> Area of ".$this->shape."\n";
}

//Method Overloading
public function __call($name,$arg)
{
if($name == 'area')
switch(count($arg))
{
case 0 : return 0 ;
break;
case 1 : $area = self::PI * $arg[0];
echo ' (a='.$arg[0].')';
return $area;
break;
case 2 : $area = $arg[0] * $arg[1];
echo ' (a='.$arg[0].' b='.$arg[1].')';
return $area;

132
break;
}
}
}

$circle = new Shape();


$circle->shape = 'Circle';
echo $circle->shape.': '.$circle->area(5);

$rect = new Shape();


$rect->shape = 'Rectangle';
echo $rect->shape.': '.$rect->area(5, 10);

$sqre = new Shape();


$sqre->shape = 'Square';
echo $sqre->shape.': '.$sqre->area(10, 10);
?>

OUTPUT:
Overloading in PHP (Property/Member and Method)

Setting 'shape' to 'Circle'


Area of Circle (a=5): 15.71

Setting 'shape' to 'Rectangle'


Area of Rectangle (a=5 b=10): 50

Setting 'shape' to 'Square'


Area of Square (a=10 b=10): 100

LAB PROGRAM - 6

6. Write a Program illustrating Object Cloning functionality in PHP?

6_objectCloning.php

<?php
class cloningObjects
{
public $name;
private $marks;

function __construct($a, $b)


{

133
$this->name = $a;
$this->marks = $b;
}

function __clone()
{
$this->marks = 90; //Private members can't be assigned values Outside the class
}
}
print("<br>Object Cloning<br>");
$a = new cloningObjects("ankur" , 50);
$b = $a; //Assigning Copy of the object (Copy by Reference on default)
print("<br> Original Object A<br>");
echo '<pre>';
print_r($a);
echo '</pre>';
$c = clone $a; //clone of the object
$a->name = "Dummy";
print("After Assigning Object A to B:");
echo '<pre>';
print_r($a);
echo '</pre>';

print("<br> Copied Object B<br>");


echo '<pre>';
print_r($b);
echo '</pre>';

print("<br> Object C (Clone Object) <br>");


echo '<pre>';
print_r($c);
echo '</pre>';
?>
OUTPUT:

Object Cloning

Original Object A
cloningObjects Object
(
[name] => ankur
[marks:cloningObjects:private] => 50
)
After Assigning Object A to B:
cloningObjects Object
(

134
[name] => Dummy
[marks:cloningObjects:private] => 50
)

Copied Object B
cloningObjects Object
(
[name] => Dummy
[marks:cloningObjects:private] => 50
)

Object C (Clone Object)


cloningObjects Object
(
[name] => ankur
[marks:cloningObjects:private] => 90
)
LAB PROGRAM - 7

7. Write a PHP program on different File Operations – creation, read, write and Displaying file contents?

7_fileOperations.php

<?php
//Creates file "textFile.txt" if doesnot exist else Opens existing file
$file = fopen("textFile.txt", "w+") or exit("Unable to create the file!");
$txt = "\nJane Doe";
fwrite($file, $txt);
fclose($file); //Closing file

//Re-open file in Append mode, pointer place at the end of File


$file = fopen("textFile.txt", "a+") or exit("Unable to open the file!");

$txt = "\nThis is Sample Text \nThis is Sample Text \nThis is Sample Text";
fwrite($file, $txt);
rewind($file); //Moving pointer to the beginning of the file

//Printing file contents Line by line


while(!feof($file))
{
echo fgets($file). "<br />";
}

fclose($file);
?>
OUTPUT:
Jane Doe
This is Sample Text

135
This is Sample Text
This is Sample Text

LAB PROGRAM - 8

8. Write a PHP program using String Functions, User provided Text?

8_stringFunc.php
<!DOCTYPE html>
<html>
<head>
<title>String Operations</title>
</head>
<body>
<form action="" name="form1" method="post">
Provide Text to do String Operations:
<br><textarea name="info" cols=50 rows=12><?php if(isset($_POST['info']) &&
$_POST['info']!='') echo $_POST['info'];?></textarea>
<br><br><input type="submit" value="Submit String" name="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['info']) && $_POST['info']!='') {
$info = $_POST['info'];
//Calculate string length
$len = strlen($info);
echo '<br><b>"Length of Provided String:</b> " '.$len;

//Find Substring
$sub = substr($info, 3, 10);
echo '<br><br>"<b>Sub String from pos 4 to pos 10 is: </b>" '.$sub;

//String Position
$pos = strpos($info, "hi");
if($pos === FALSE)
echo '<br><br><b>String "hi" not found</b>';
else
echo '<br><br><b>String "hi" is found at Position: </b>'.($pos==0 ? 1 : $pos);

//SubString replaced with "BCA 5th Semester"


$str = str_replace($sub, "<b>BCA 5th Semester </b>",$info);
echo '<br><br><b>The Above SubString is replaced with "BCA 5th
Semester</b>":<br><br>'.$str;
}

136
?>
OUTPUT:

LAB PROGRAM – 9
9. Write a PHP Program to validate Email and Domain Name (Matching Patterns)?

9_formValidate.php
<!DOCTYPE html>
<html>
<head>
<title>Process the HTML form data with the POST method</title>
</head>
<style>
.box {
position: fixed;
top: 10%;
left: 20%;
margin: 40px;
}
body {
margin:15px 0 40px 0; padding:0px; background:url('bk_image.jpeg') no-repeat;
background-size: cover;
}

}</style>
<body>
<div class="box">
<?php
if(isset($_POST["email"]))
{
// Pattern for checking Email
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$email = $_POST["email"];

if (preg_match($pattern,$email))
echo '"'.$email.'" Email is VALID';
else

137
echo '"'.$email.'" Email is INvalid';
}

if(isset($_POST["domain"]))
{
$testURL = $_POST["domain"];
if(chkURL($testURL))
print('<br>Given Domain "'.$testURL.'" is VALID');
else
print('<br>Given Domain "'.$testURL.'" is INvalid');
}

//Pattern for checking Domain names


function chkURL($url)
{
$pattern = '^www\.[a-z.]+\.com$';
return(preg_match('/'.$pattern.'/', $url));
//return(ereg($pattern, $url));
}
?>
<form name="myform" action="" method="post">
<br /><br />
Domain: <input type="text" name="domain" /><br />
<br />
Email: <input type="text" name="email" /><br /> <br />

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="submit"


name="submit" />
</div>
</form>
</body>
</html>

LAB PROGRAM - 10

10. Write a PHP program to Upload an Image?

138
10_formUpload.php

<?php
if(isset($_GET['status']) && $_GET['status']!='') {
$st = $_GET['status'];
switch($st) {
case 0: echo "<br>Sorry, there was an error uploading your file";
break;
case 1: echo "<br>File has been uploaded Successfully";
break;
case 2: echo "<br>File is an image, not uploaded";
break;
case 3: echo "<br>Uploaded file is not an Image";
break;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form to Upload an Image</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<br><br>Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<br><br><input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$st = 2;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$st = 1;
} else $st = 0;

139
}
else $st = 3;
}
header("Location: 11_formUpload.php?status=".$st);
?>

OUTPUT:

LAB PROGRAM - 11

11. Write a PHP program on Session Management (Login Functionality)?

11_niceform.php

<?php
session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
header("Location: content.php");
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> PHP Login </title>
</head>
<body>
<center>
<form method="post" action="login_withoutDB.php">
<!-– In this example I link it with login.php to check the password & username -–>
<table>
<tr><td>Username:</td><td><input type="text" name="usr"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pswd"></td></tr>
<tr><td><input type="submit" name="login" value="Login"></td>
<td><input type="reset" name="reset" value="Reset"></td></tr>
</table>
</form>
</center>
</body>
</html>
login_withoutDB.php
<?php
session_start();

140
if($_REQUEST['usr']=="ABC" && $_REQUEST['pswd']=="123"){
$_SESSION['usr'] = "ABC";
$_SESSION['pswd'] = "123";
header("Location: content.php");
}
else{
header("Location: niceform.php");
}
?>
content.php
<?php
session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
header("Location: niceform.php");
}
include 'logoff.html';
?>
logoff.html
<html>
<head>
<title></title>
</head>
<body>
<center>
<h2><a href="./logout.php">Logout</a></h2>
<br/>
</center>
</body>
</html>
logout.php
<?php
session_start();
session_destroy();
header('Location: 11_niceform.php');
exit;
?>

OUTPUT:

141
LAB PROGRAM - 12

12. Write a PHP program to INSERT user details into MySQL database?

12_mysqlInsertQry.php
<?php
include("dbConnect.php");

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY id DESC";


$result = $conn->query($sql);
if($result->num_rows)
echo 'Existing Number of Records in the Table: '.$result->num_rows;

if(isset($_POST['submit']) && $_POST['submit'] == "INSERT")


{
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('".$_POST['fname']."',
'".$_POST['lname']."', '".$_POST['email']."')";

if ($conn->query($sql) === TRUE) { //mysqli_query($conn, $sql)


$last_id = $conn->insert_id; //mysqli_insert_id($conn)
$status = 1;
} else {
$status = 0;
}

//$conn->multi_query($sql) === TRUE) //If u want to execute multiple queries where $sql
contains multiple insert queries

$conn->close();
header("Location: 12_mysqlInsertQry.php?st=".$status);
}
if(isset($_GET['st']))
{
if($_GET['st'] == 1)
echo "<br><br>New record inserted successfully";
else
echo "Error: " . $sql . "<br>" . $conn->error;
}
include("userForm.php");
?>
dbConnect.php
<?php
$servername = "localhost";
$username = "root";

142
$password = "";
$dbname = "2017bca5";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
userForm.php
<html>
<body>
<br><br>
<b><u>FORM TO ENTER DETAILS</u></b>
<form name="form1" method="post"><br><br>
First Name: <input type="text" name="fname" /><br><br>
Last Name: <input type="text" name="lname" /><br><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email: <input type="text"
name="email" /><br><br>
<input type="submit" name="submit" value="INSERT" /><br>
</form>
</body>
</html>

Note: In database (2017bca5), create the following table


CREATE TABLE IF NOT EXISTS `myguests` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`firstname` varchar(20) NOT NULL,
`lastname` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

OUTPUT:

143
LAB PROGRAM - 13

13. Write a PHP program to UPDATE user details on MySQL database?

13_mysqlUpdateQry.php
<?php
include("dbConnect.php");

//For Reading Records


$sql = "SELECT * FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
echo "<table>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Email</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. "</td><td>" .
$row["lastname"]. "</td><td>" . $row["email"]. '</td><td><a
href="userUpdateForm.php?id='.$row["id"].'">EDIT</a></tr>';
}
echo "</table>";
} else {
echo "0 results";
}

$conn->close();
?>
dbConnect.php //same file provided for above program

userUpdateForm.php
144
<?php
include("dbConnect.php");

if(isset($_POST['submit']) && $_POST['submit'] == "UPDATE")


{
$sql = "UPDATE MyGuests SET firstname='".$_POST['fname']."',
lastname='".$_POST['lname']."', email='".$_POST['email']."' WHERE id=".$_GET['id'];

if ($conn->query($sql) === TRUE)


{
$conn->close();
header("Location: displayRec.php");
}
}

$sql = "SELECT * FROM MyGuests WHERE id=".$_GET['id'];


$result = $conn->query($sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
?>
<html>
<body>
<br><br>
<b><u>FORM TO UPDATE DETAILS</u></b>
<form name="form1" method="post"><br><br>
First Name: <input type="text" name="fname" value="<?php echo $row["firstname"];?>"
/><br><br>
Last Name: <input type="text" name="lname" value="<?php echo $row["lastname"];?>"
/><br><br>
Email: <input type="text" name="email" value="<?php echo $row["email"];?>" /><br><br>
<input type="submit" name="submit" value="UPDATE" /><br>
</form>
</body>
</html>
displayRec.php
<?php
include("dbConnect.php");
//For Reading Records
$sql = "SELECT * FROM MyGuests ORDER BY id DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
echo '<table cellpadding="10">';
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Email</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<td>" . $row["id"]. "</td><td>" . $row["firstname"]. "</td><td>" .
$row["lastname"]. "</td><td>" . $row["email"]. "</td></tr>";
}
echo "</table>";
} else {

145
echo "0 results";
}
?>
OUTPUT:

LAB PROGRAM - 14

14. Write a PHP program for RETRIEVING Guest Information using MySQL Stored Procedures?

14_storedProcedures.php
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Stored Procedure Demo</title>
</head>
<body>
<?php
echo "Demo on PDO and MySQL Stored Procedures<br><br>";
$host = 'localhost';
$dbname = '2017bca5';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// execute the stored procedure
$sql = 'CALL GetGuests()';
// call the stored procedure
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
?>
<table>
<tr>
<th>First Name</th>
<th>Email</th>
</tr>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo $r['firstname']; ?></td>
<td><?php echo $r['email']; ?>
</td>
</tr>

146
<?php endwhile; ?>
</table>
</body>
</html>
Note: Execute the following stored procedure in phpmyadmin (on Database)
DELIMITER $$
CREATE PROCEDURE GetGuests( )
BEGIN
SELECT firstname, email FROM myguests;
END

OUTPUT:

LAB PROGRAM - 15

15. Write a PHP program for Deleting User Information and keeping track of deleted records using
MySQL Triggers?

15_triggerDeleteQry.php

<script language="javascript" type="text/javascript">


function deleteEmp(empID)
{
var r = confirm("Are you sure to delete! Press ok to Continue ");
if (r == true)
{
window.location="15_triggerDeleteQry.php?delID="+empID;
return true;
}
}
</script>

<?php
include("dbConnect.php");

if(isset($_GET['delID']) && $_GET['delID']>0)


{
$sql = "DELETE FROM myguests WHERE id = ".$_GET['delID'];
$result = $conn->query($sql);
}

//For Reading Records

147
$sql = "SELECT * FROM myguests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
echo "<table>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Email</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. "</td><td>" .
$row["lastname"]. "</td>";
echo "<td>" . $row["email"]. '</td><td><a
onclick="deleteEmp('.$row['id'].');">DELETE</a></tr>';
}
echo "</table>";
} else {
echo "0 results";
}

$conn->close();
?>

CREATE TABLE track_guest (


id INT AUTO_INCREMENT PRIMARY KEY,
guestNumber INT NOT NULL,
lastname VARCHAR(50) NOT NULL,
changedate DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL
);

CREATE TRIGGER `before_guest_delete` BEFORE DELETE ON `myguests` FOR EACH ROW


BEGIN
INSERT INTO track_guest
SET action = 'delete',
guestNumber = OLD.id,
lastname = OLD.lastname,
changedate = NOW();
END

148

You might also like