PHP Notes
PHP Notes
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;
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
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.
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.
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.
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!
If you use this style, you can be positive that your tags will always be correctly interpreted.
<?...?>
Short tags are, as one might expect, the shortest option You must do one of two things to enable
PHP to recognize the 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
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
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";
?>
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
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.
<?php
//Commented lines starting with the double forward slash will be ignored by PHP
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";
There are a few rules that you need to follow when choosing a name for your PHP variables.
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");
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.
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.
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;
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;
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.
<?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 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:
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%";
echo "</tr>";
}
echo "</table>";
?>
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:
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.
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>";
$i = 0;
$j = 0;
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>";
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)
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;
?>
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.
<?php
$seven = 7;
$arrayname = array( "this is an element", 5, $seven );
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
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
Declaring functions
A function is created with the function keyword. simple.php
<?php
function displayVersion() {
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.
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;
}
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) {
return $x;
} else {
return $y;
}
}
$a = 23;
$b = 32;
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.
The value returned by the maximum() function is assigned to the $val variable.
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) {
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
?>
recursion.php
<?php
32
function factorial($n) {
if ($n==0) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
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();
?>
Hello
$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.
function foo() {
// returns an array of all passed arguments
$args = func_get_args();
<?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.
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";
// send email
mail("someone@example.com","My subject",$msg);
?>
// 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 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 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.
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!
<?php
require("xxmenu.php");
?>
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.
“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.
If a calling script does not find a called script with the include_once statement, it halts the
execution of the calling script.
Class
Objects
Inheritance
Interface
Abstraction
Magic Methods
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.
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.
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 ->.
Constant
1. Always public cannot put access modifiers.
class A{
const my_constant = "constant value";
public const wrong_constant="wrong" // produce a parse error
}
42
3. Cannot change the value after declaration.
self::variable_name = "cannot change"; //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
}
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
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:
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/>';
}
}
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
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.
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
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';
function iterateVisible() {
echo "MyClass::iterateVisible:\n";
foreach ($this as $key => $value) {
print "$key => $value\n";
}
}
}
$class->iterateVisible();
?>
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.
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
$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.
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.
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
}
}
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.
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.
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
$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)
59
path $options = PATHINFO_DIRNAME |
PATHINFO_BASENAME |
PATHINFO_EXTENSION |
PATHINFO_FILENAME ] )
fileperms () Returns the permissions of a file int fileperms ( string $filename )
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).
60
Syntax: array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [,
resource $context ]] ) //Returns an array of files and directories from the directory.
<?php
if(!is_dir("testing"))
mkdir("testing","777");
/*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.
<?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";
?>
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
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;
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
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>
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
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:
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.
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.
PHP currently offers following functions for searching strings using POSIX-style regular
expressions
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 –
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'.
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)
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.
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:
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.
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
?>
$_COOKIE array can contain depends on the memory size set in php.ini.
Let’s assume you have saved your PHP files in php folder.
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
?>
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.
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
If you want to destroy only a session single item, you use the unset() function.
<?php
?>
Session_destroy removes all the session data including cookies associated with the session.
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.
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:
78
HERE,
OR
79
$_GET['variable_name']; Eg: $_GET['firstname']
?>
HERE,
“$_GET[…]” is the PHP array
“'variable_name'” is the URL variable name.
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).
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.
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 enabled to specifically report all errors, but not notices:
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:
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");
?>
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.
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.
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.
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:
<?php
echo "Hi this is codex-m";
?>
2.) Open another blank text file and enter this code:
<?php
header(‘Location: http://localhost/targetpage.php’);
?>
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”.
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,
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.
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
Function Description
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:
<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/MSIE/i', $user_agent)) {
echo "Internet Explorer";
} else {
echo "Non-IE Browser";
}
?>
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.
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.
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:
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
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:
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:
CREATE TABLE
The MySQL CREATE TABLE command is used to create a new table into the database. A table
creation command requires three things:
Syntax: Following is a generic syntax for creating a MySQL table in the database.
Example:
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:
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.
Code:
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).
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 |
+----------+--------+---------+------+------------+------------+
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:
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:
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;
SHOW TABLES;
SHOW TABLES FROM db_name;
String Datatypes
The following are the String Datatypes in MySQL:
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:
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
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');
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);
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 following MySQL statement will find the smallest out of the list of arguments.
SELECT LEAST(15,10,25); //Returns 10
100
NOT LIKE
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:
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:
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.
4. TCL(transaction Control Language) : TCL commands deals with the transaction within the
database.
Syntax
CREATE DATABASE databasename;
102
MySQL ALTER DATABASE
The ALTER DATABASE statement is used to modify, maintain, or recover an existing database.
alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
To rename the mysql database, you need to follow the following syntax:
Syntax
DROP DATABASE databasename;
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.).
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.
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
To change the data type of a column in a table, use the following syntax:
Syntax
DROP TABLE table_name;
Example
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;
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.
Where {tbl_name} table that exists in the current database, and {new_tbl_name} is new
table name.
UNIT - 4
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';
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:
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.
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".
Example
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
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:
107
+----------+
| 0|
+----------+
1 row in set (5.02 sec)
mysql> DO SLEEP(5);
Query OK, 0 rows affected (4.99 sec)
REPLACE Statement
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,
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
Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
The WHERE clause is very useful when you want to update the selected rows in a table.
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:
MySQL Subqueries
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.
mysql> CREATE TABLE tb1 (c1 INT, c2 CHAR(5), c3 FLOAT); Query OK, 0 rows affected (0.73 sec)
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)
Here is how to use a subquery in the FROM clause, using the example table (tb1):
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
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.
DELIMITER $$
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
MYSQL 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 CUSTOMERLEVEL(creditlim)
INTO customerLevel;
END
113
CREATE PROCEDURE GetCustomers()
BEGIN
SELECT CustomerName, creditlimit FROM customers;
END
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.
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
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:
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
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.
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:
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:
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.
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
Granting Privileges
118
mysql>GRANT DELETE ON books.authors TO 'michele'@'192.168.1.103';
mysql>GRANT SELECT,INSERT,DELETE ON
->books.authors TO 'rita'@'%.wjgilmore.com'
->IDENTIFIED BY 'secret';
Revoking Privileges
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
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:
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>
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
2A_simpleMail.php
<?php
$to = 'pavani@cavalier.com';
$subject = 'Examination TimeTable';
$from = 'admin@cavalier.com';
// 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:
LAB PROGRAM – 2B
2. B. Write a program on illustrating Constructor and Destructor in PHP?
2B_ConstDest.php
<?php
class numbers
{
public $a, $b;
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) {
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> </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> </td></tr>
<tr><td height="40"><input type="radio" name="oper" id="oper_rand" value="rand"
/>Pick a Random value from Array</td><td> </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;
}
}
}
OUTPUT:
Overloading in PHP (Property/Member and Method)
LAB PROGRAM - 6
6_objectCloning.php
<?php
class cloningObjects
{
public $name;
private $marks;
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>';
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
)
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
$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
fclose($file);
?>
OUTPUT:
Jane Doe
This is Sample Text
135
This is Sample Text
This is Sample Text
LAB PROGRAM - 8
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);
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');
}
LAB PROGRAM - 10
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_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");
//$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>
Email: <input type="text"
name="email" /><br><br>
<input type="submit" name="submit" value="INSERT" /><br>
</form>
</body>
</html>
OUTPUT:
143
LAB PROGRAM - 13
13_mysqlUpdateQry.php
<?php
include("dbConnect.php");
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 ($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
<?php
include("dbConnect.php");
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();
?>
148