Advanced Webpage Compiled Note1
Advanced Webpage Compiled Note1
PHP Programming
Contents Pages
Inheritance ................................................................................................................................................... 81
Function Overriding ..................................................................................................................................... 82
Public Members ....................................................................................................................................... 82
Private members ...................................................................................................................................... 82
Protected members .................................................................................................................................. 83
Interfaces ...................................................................................................................................................... 84
Constants...................................................................................................................................................... 84
Abstract Classes ........................................................................................................................................... 84
Static Keyword ........................................................................................................................................ 85
Final Keyword ......................................................................................................................................... 85
Calling parent constructors ...................................................................................................................... 86
Glossary ................................................................................................................................... 88
PHP 5 MySQLi Functions ................................................................................................................ 88
PHP Date and Time Functions .......................................................................................................... 91
PHP Calendar Functions ................................................................................................................... 93
Chapter One
Static vs. Dynamic Websites
Websites that only use HTML and CSS are called static websites, and websites with scripting are
called dynamic websites. When thinking about making your website, it’s important to identify which
type of site you want. To help you decide, here’s an explanation on static vs. dynamic websites.
A Static Website
A static website is the simplest kind of website you can build. Static websites are written in HTML
and CSS only, with no scripting. The only form of interactivity on a static website is hyperlinks.
If you intend your website to be a small one (3 pages or less), then a static website might be
the easiest way to go. But if you want to share elements between pages (such as logos or
menus), you’ll have to duplicate the HTML on each page.
Static websites are easier to make than dynamic websites, because they require less coding
and technical knowledge. However, fully static websites are very uncommon these days,
since there is so much that scripting can do.
A Dynamic Website
A dynamic website is a website that not only uses HTML and CSS, but includes website
scripting as well. There are two main reasons why you’d want to use website scripting on
your site:
1. you want an interactive web app that people can use, not just read
2. You want to be able to share HTML code between your pages.
The software being distributed must be redistributed to anyone else without any
restriction.
The source code must be made available (so that the receiving party will be able to
improve or modify it).
The license can require improved versions of the software to carry a different name or
version from the original software.
What is PHP?
PHP is a server-side scripting language designed primarily for web development but is also
used as a general-purpose programming language. Originally created by Rasmus Lerdorf in
1994, the PHP reference implementation is now produced by The PHP Development Team.
PHP is an open source, interpreted and object-oriented scripting language i.e. executed at
server side. It is used to develop web applications (an application i.e. executed at server side
and generates dynamic page).
Short........!
PHP Features
o Performance: Script written in PHP executes much faster then those scripts written in
other languages such as JSP & ASP.
o Open Source Software: PHP source code is free available on the web, you can
developed all the version of PHP according to your requirement without paying any
cost.
o Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
o Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and script.
Install PHP
To install PHP, suggest you to install AMP (Apache, MySQL, PHP) software stack. It is available for all
operating systems. There are many AMP options available in the market that are given below:
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other components
too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.
What is MYSQL?
MySQL is a freely available open source Relational Database Management System (RDBMS) that
uses Structured Query Language (SQL).
SQL is the most popular language for adding, accessing and managing content in a database. It is
most noted for its quick processing, proven reliability, ease and flexibility of use. MySQL is an
essential part of almost every open source PHP application. Good examples for PHP/MySQL-based
scripts are phpBB, osCommerce and Joomla.
Apache is the most widely used web server software. Developed and maintained by Apache Software
Foundation, Apache is an open source software available for free. It runs on 67% of all web servers in
the world. It is fast, reliable, and secure. It can be highly customized to meet the needs of many
different environments by using extensions and modules. Most WordPress hosting providers use
Apache as their web server software. However, WordPress can run on other web server software as
well.
So basically a web server is the software that receives your request to access a web page. It runs a few
security checks on your HTTP request and takes you to the web page. Depending on the page you
have requested, the page may ask the server to run a few extra modules while generating the
document to serve you. It then serves you the document you requested. Pretty awesome isn’t it?
Chapter Two
PHP Fundamentals
PHP Introduction
PHP Three letters that together constitutes the name of one of the world’s most popular programming
languages for Web development, the PHP Hypertext Pre-processor.
While you might chuckle at the greenness of the recursive acronym, statistics indicate that PHP is not
be taken lightly: the language is today in use on over twenty million Web sites and more than a third
of the world’s Web servers-no small feat, especially when you consider that the language has been
developed entirely by a worldwide community of volunteers and is freely available on the Internet at
no cost whatsoever!
Over the last few years, PHP has become the de facto choice for the development of data-driven Web
applications, notably on account of its scalability, ease of use, and widespread support for different
databases and data formats.
This first chapter will gently introduce you to the world of PHP, by taking you on a whirlwind tour of
PHP’s history and features, and then guiding you through writing and executing your first PHP
program So flip the page, and let’s get Started.
History of PHP
PHP was originally created by a developer named Rasmus Lerdorf in 1995.
Why PHP?
Unique Features
If you are familiar with other server side language like ASP.NET or JSP you might be wondering
what makes PHP so special or so different from these competing alternatives well, here are some
reasons:
1. Performance
2. Portability(Platform Independent)
3. Ease Of Use
4. Open Source
5. Third-Party Application Support
6. Community Support
Performance
Scripts written in PHP executives faster than those written in other scripting language, with
numerous independent benchmarks, putting the language ahead of competing alternatives like
JSP, ASP.NET and PERL. The PHP 5.0 engine was completely redesigned with an optimized
memory manager to improve performance, and is noticeable faster than previous versions. In
addition, third party accelerators are available to further improve performance and response time.
Portability
PHP is available for UNIX, MICROSOFT WINDOWS, MAC OS, and OS/2.PHP Programs are
portable between platforms. As a result, a PHP application developed on, say, Windows will
typically run on UNIX without any significant issues. This ability to easily undertake cross-
platform development is a valuable one, especially when operating in a multi platform corporate
environment or when trying to address multiple market segments.
Ease of Use
“Simplicity is the ultimate sophistication”, Said Leonardo da Vinci, and by that measure, PHP is
an extremely sophisticated programming language. Its syntax is clear and consistent, and it comes
with exhaustive documentation for the 5000+ functions included with the core distributions. This
significantly reduces the learning curve for both novice and experienced programmers, and it’s
one of the reasons that PHP is favoured as a rapid prototyping tool for Web-based applications.
Open Source
PHP is an open source project – the language is developed by a worldwide team of volunteers
who make its source code freely available on the Web, and it may be used without payment of
licensing fees or investments in expensive hardware or software .This reduces software
development costs without affecting either flexibility or reliability The open-source nature of the
code further means that any developer, anywhere , can inspect the code tree, spit errors, and
suggest possible fixes, this produces a stable, robust product wherein bugs, once discovered, are
rapidly resolved – sometimes within a few hours of discovery !.
Community Support
One of the nice things about a community-supported language like PHP is the access it offers to
the creativity and imagination of hundreds of developers across the world. Within the PHP
community, the fruits of this creativity may be found in PEAR, the PHP Extension and
Application Repository and PECL, the PHP Extension Community Library, which contains
hundreds of ready-, made widgets and extensions that developers can use to painlessly and new
functionality to PHP. Using these widgets is often a more time-and cost-efficient alternative to
rolling your own code.
PHP Basic
PHP Echo
PHP echo is a language constructs not a function, so you don't need to use parenthesis with it. But if you want to
use more than one parameters, it is required to use parenthesis.
PHP echo statement can be used to print string, multi line strings, escaping characters, variable, array etc.
File: echo1.php
<?php
echo "Hello by PHP echo";
?>
Output:
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument list.
Unlike echo, it always returns 1.
PHP print statement can be used to print string, multi line strings, escaping characters, variable, array etc.
File: print1.php
<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
?>
Output:
PHP Variables
A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is used to
store data temporarily.
$variablename=value;
Let's see the example to store string, integer and float values in PHP variables.
File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script. PHP constants can
be defined by 2 ways:
PHP constants follow the same PHP variable rules. For example, it can be started with letter or underscore only.
File: constant1.php
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
Output:
Output:
File: constant3.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>
Output:
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized
further in 3 types:
1. Scalar Types
2. Compound Types
3. Special Types
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. For example:
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
o Arithmetic Operators
o Comparison Operators
o Bitwise Operators
o Logical Operators
o String Operators
o Incrementing/Decrementing Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
o Assignment Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right
| bitwise OR left
|| logical OR left
?: ternary left
or logical left
PHP Comments
PHP comments can be used to describe any line of code so that other developer can understand the code easily. It can also be
used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style (Unix shell style)
comments.
<?php
// this is C++ style single line comment
# this is Unix Shell style single line comment
echo "Welcome to PHP single line comments";
?>
Output:
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */. Let's see a simple example
of PHP multiple line comment.
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>
Output:
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
o if
o if-else
o if-else-if
o nested if
PHP If Statement
Syntax
if(condition){
//code to be executed
}
Flowchart
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Flowchart
Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output:
12 is even number
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Flowchart
Example
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20
PHP for loop can be used to traverse set of code for the specified number of times.
Syntax
Flowchart
Example
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
We can use for loop inside for loop in PHP, it is known as nested for loop.
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed
for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd
outer loop and 3 times for 3rd outer loop).
Example
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
?>
Output:
11
12
13
21
22
23
31
32
33
Syntax
Example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>
Output:
PHP while loop can be used to traverse set of code like for loop.
Syntax
while(condition){
//code to be executed
}
Alternative Syntax
while(condition):
//code to be executed
endwhile;
Flowchart
Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
Alternative Example
<?php
$n=1;
while($n<=10):
echo "$n<br/>";
$n++;
endwhile;
?>
Output:
1
2
3
4
5
6
7
8
9
10
We can use while loop inside another while loop in PHP, it is known as nested while loop.
In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be
executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer
loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
Example
<?php
$i=1;
while($i<=3){
$j=1;
while($j<=3){
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>
Output:
11
12
13
21
22
23
31
32
33
PHP do while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at
least once.
It executes the code at least one time always because condition is checked after executing the code.
Syntax
do{
//code to be executed
}while(condition);
Flowchart
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP Break
PHP break statement breaks the execution of current for, while, do-while, switch and for-each loop. If you use break inside
inner loop, it breaks the execution of inner loop only.
Syntax
1. jump statement;
2. break;
Flowchart
Let's see a simple example to break the execution of for loop if value of i is equal to 5.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1
2
3
4
5
The PHP break statement breaks the execution of inner loop only.
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
Output:
11
12
13
21
22
31
32
33
The PHP break statement breaks the flow of switch case also.
<?php
$num=200;
switch($num){
case 100:
echo("number is equals to 100");
break;
case 200:
echo("number is equal to 200");
break;
case 50:
echo("number is equal to 300");
break;
default:
echo("number is not equal to 100, 200 or 500");
}
?>
Output:
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are
thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive function also.
Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming
languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of function, you can write
the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application
because every logic is divided in the form of functions.
We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined functions.
Syntax
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be start
with numbers or special symbols.
Example
File: function1.php
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length argument list.
File: functionarg.php
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
Hello Sonoo
Hello Vimal
Hello John
File: functionarg2.php
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Value passed to the function doesn't modify the actual value by default (call by value). But we can do so by passing value as
a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to use ampersand (&) symbol
before the argument name.
File: functionref.php
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
1. ?>
Output:
We can specify a default argument value in function. While calling PHP function if you don't specify any argument, it will
take the default argument. Let's see a simple example of using default argument value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
PHP allows you to call function by value and reference both. In case of PHP call by value, actual value is not modified if it is
modified inside the function.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with 'Call By Value' string. But,
printing $str variable results 'Hello' only. It is because changes are done in the local variable $str2 only. It doesn't reflect to
$str variable.
<?php
function adder($str2)
{
Output:
Hello
Example 2
Let's understand PHP call by value concept through another example.
<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
10
In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use
& (ampersand) symbol with formal arguments. The & represents reference of the variable.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with 'Call By Reference' string. Here,
printing $str variable results 'This is Call By Reference'. It is because changes are done in the actual variable $str.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:
Example 2
Let's understand PHP call by reference concept through another example.
<?php
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
11
PHP allows you to define C++ style default argument values. In such case, if you don't pass any value to the function, it will
use default argument value.
Let' see the simple example of using PHP default arguments in function.
Example 1
<?php
function sayHello($name="Ram"){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello();//passing no value
sayHello("Vimal");
?>
Output:
Hello Sonoo
Hello Ram
Hello Vimal
Since PHP 5, you can use the concept of default argument value with call by reference also.
Example 2
<?php
function greeting($first="Sonoo",$last="Jaiswal"){
echo "Greeting: $first $last<br/>";
}
greeting();
greeting("Rahul");
greeting("Michael","Clark");
?>
Output:
Example 3
<?php
function add($n1=10,$n2=10){
$n3=$n1+$n2;
echo "Addition is: $n3<br/>";
}
add();
add(20);
add(40,40);
?>
Output:
Addition is: 20
Addition is: 30
Addition is: 80
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do so,
you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
1. <?php
2. function add(...$numbers) {
3. $sum = 0;
4. foreach ($numbers as $n) {
5. $sum += $n;
6. }
7. return $sum;
8. }
9.
10. echo add(1, 2, 3, 4);
11. ?>
Output:
10
PHP also supports recursive function call like C/C++. In such case, we call current function within function. It is also known
as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may smash the stack and may cause
the termination of script.
Output:
1
2
3
4
5
Output:
120
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single
variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP
array elements are assigned to an index number by default.
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
We can associate name with each array elements in PHP using => symbol.
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by
an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.
Definition
Compiled By: Maregu Assefa 34
September 1, 2016 Advanced Webpage Design and Development
1st way:
1. $size=array("Big","Medium","Short");
2nd way:
1. $size[0]="Big";
2. $size[1]="Medium";
3. $size[2]="Short";
Example
File: array1.php
1. <?php
2. $size=array("Big","Medium","Short");
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>
Output:
Output:
We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all the elements of PHP array.
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Output:
1.
2. <?php
3. $size=array("Big","Medium","Short");
4. echo count($size);
5. ?>
Output:
PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you can easily
remember the element because each element is represented by label than an incremented number.
Definition
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>
Output:
Output:
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP
multidimensional array can be represented in the form of matrix which is represented by row * column.
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
Example
Let's see a simple example of PHP multidimensional array to display following tabular data. In this example, we are
displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are
given below.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer
PHP array_search() function searches the specified value in an array. It returns key if search is successful.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching elements of two
array.
Syntax
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith
PHP Strings
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4 ways to specify string in PHP.
o single quoted
o double quoted
o heredoc syntax
o newdoc syntax (since PHP 5.3)
We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify string in PHP.
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
We can store multiple line text, special characters and escape sequences in a single quoted PHP string.
1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
Note: In single quoted PHP strings, most escape sequences and variables will not be interpreted. But, we can
use single quote through \' and backslash through \\ inside single quoted PHP strings.
1. <?php
2. $num1=10;
3. $str1='trying variable $num1';
4. $str2='trying backslash n and backslash t inside single quoted string \n \t';
5. $str3='Using single quote \'my quote\' and \\backslash';
6. echo "$str1 <br/> $str2 <br/> $str3";
7. ?>
Output:
In PHP, we can specify string through enclosing text within double quote also. But escape sequences and variables will be
interpreted using double quote PHP strings.
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Output:
Now, you can't use double quote directly inside double quoted string.
1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>
Output:
We can store multiple line text, special characters and escape sequences in a double quoted PHP string.
1. <?php
2. $str1="Hello text
3. multiple line
4. text within double quoted string";
5. $str2="Using double \"quote\" with backslash inside double quoted string";
6. $str3="Using escape sequences \n in double quoted string";
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>
Output:
Number is: 10
PHP provides various string functions to access and manipulate strings. A list of important PHP string functions are given
below.
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>
Output:
my name is khan
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>
Output:
MY NAME IS KHAN
Syntax
Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>
Output:
My name is KHAN
Syntax
Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:
mY name IS KHAN
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>
Output:
24
Chapter Three
PHP Math Functions
PHP provides many predefined math constants and functions that can be used to perform mathematical operations.
Syntax
1. number abs ( mixed $number )
Example
1. <?php
2. echo (abs(-7)."<br/>"); // 7 (integer)
3. echo (abs(7)."<br/>"); //7 (integer)
4. echo (abs(-7.2)."<br/>"); //7.2 (float/double)
5. ?>
Output:
7
7
7.2
Syntax
1. float ceil ( float $value )
Example
1. <?php
2. echo (ceil(3.3)."<br/>");// 4
3. echo (ceil(7.333)."<br/>");// 8
4. echo (ceil(-4.8)."<br/>");// -4
5. ?>
Output:
4
8
-4
Syntax
1. float floor ( float $value )
Example
1. <?php
2. echo (floor(3.3)."<br/>");// 3
3. echo (floor(7.333)."<br/>");// 7
4. echo (floor(-4.8)."<br/>");// -5
5. ?>
Output:
3
7
-5
Syntax
1. float sqrt ( float $arg )
Example
1. <?php
2. echo (sqrt(16)."<br/>");// 4
3. echo (sqrt(25)."<br/>");// 5
4. echo (sqrt(7)."<br/>");// 2.6457513110646
5. ?>
Output:
4
5
2.6457513110646
Syntax
1. string decbin ( int $number )
Example
1. <?php
2. echo (decbin(2)."<br/>");// 10
3. echo (decbin(10)."<br/>");// 1010
4. echo (decbin(22)."<br/>");// 10110
5. ?>
Output:
10
1010
10110
Syntax
1. string dechex ( int $number )
Example
1. <?php
2. echo (dechex(2)."<br/>");// 2
3. echo (dechex(10)."<br/>");// a
4. echo (dechex(22)."<br/>");// 16
5. ?>
Output:
2
a
16
Syntax
1. string decoct ( int $number )
Example
1. <?php
2. echo (decoct(2)."<br/>");// 2
3. echo (decoct(10)."<br/>");// 12
4. echo (decoct(22)."<br/>");// 26
5. ?>
Output:
2
12
26
Syntax
1. string base_convert ( string $number , int $frombase , int $tobase )
Example
1. <?php
2. $n1=10;
3. echo (base_convert($n1,10,2)."<br/>");// 1010
4. ?>
Output:
1010
Syntax
1. number bindec ( string $binary_string )
Example
1. <?php
2. echo (bindec(10)."<br/>");// 2
3. echo (bindec(1010)."<br/>");// 10
4. echo (bindec(1011)."<br/>");// 11
5. ?>
Output:
2
10
11
o abs()
o acos()
o acosh()
o asin()
o asinh()
o atan()
o atan2()
o atanh()
o base_convert()
o bindec()
o ceil()
o cos()
o cosh()
o decbin()
o dechex()
o decoct()
o deg2rad()
o exp()
o expm1()
o floor()
o fmod()
o getrandmax()
o hexdec()
o hypot()
o is_finite()
o is_infinite()
o is_nan()
o lcg_value()
o log()
o log10()
o log1p()
o max()
o min()
o mt_getrandmax()
o mt_rand()
o mt_srand()
o octdec()
o pi()
o pow()
o rad2deg()
o rand()
o round()
o sin()
o sinh()
o sqrt()
o srand()
o tan()
o tanh()
PHP Form
PHP Form Handling
We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST.
Get request is the default form request. The data passed through get request is visible on the URL browser so it is not
secured. You can send limited amount of data through get request.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form,
registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You can send large amount of data
through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
1. <form action="login.php" method="post">
2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
4. <tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
6. </table>
7. </form>
File: login.php
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>
Output:
PHP Includes
PHP Include File
PHP allows you to include file so that a page content can be reused many times. There are two ways to include file in PHP.
1. include
2. require
Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or PHP script in many PHP
scripts.
PHP include is used to include file on the basis of given path. You may use relative or absolute path of the file. Let's see a
simple PHP include example.
File: menu.html
1. <a href="index.html">Home</a> |
2. <a href="php-tutorial.html">PHP</a> |
3. <a href="java-tutorial.html">Java</a> |
4. <a href="html-tutorial.html">HTML</a>
File: include1.php
Output:
PHP require is similar to include. Let's see a simple PHP require example.
File: menu.html
1. <a href="index.html">Home</a> |
2. <a href="php-tutorial.html">PHP</a> |
3. <a href="java-tutorial.html">Java</a> |
4. <a href="html-tutorial.html">HTML</a>
File: require1.php
Output:
If file is missing or inclusion fails, include allows the script to continue but require halts the script producing a fatal
E_COMPILE_ERROR level error.
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is
embedded with request. Such way, cookie can be received at the server side.
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIE
superglobal variable.
Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
PHP $_COOKIE
Example
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14.
15. <!-- Mirrored from www.javatpoint.com/php-
cookie by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 30 Jun 2015 00:52:10 GMT -->
16. </html>
Output:
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until user close the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g. username,
product code, product name, product price etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict between multiple browsers.
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It returns existing session
if session is created already. If session is not available, it creates and returns new session.
Syntax
Example
1. session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.
1. $_SESSION["user"] = "Sachin";
1. echo $_SESSION["user"];
5. <body>
6. <?php
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.html">Visit next page</a>
11. </body>
12.
13. <!-- Mirrored from www.javatpoint.com/php-
session by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 30 Jun 2015 00:52:10 GMT -->
14. </html>
File: session2.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>
File: session3.php
1. <?php
2. session_start();
3. session_destroy();
4. ?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
Example
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Syntax
Example
1. <?php
2. fclose($handle);
3. ?>
PHP Read File - fread()
The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file size.
Syntax
Example
1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>
Output
hello php file
The PHP fwrite() function is used to write content of the string into file.
Syntax
Example
1. <?php
2. $fp = fopen('data.html', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output
Syntax
Example
1. <?php
2. unlink('data.html');
3.
4. echo "File deleted successfully";
5. ?>
PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts two arguments:
$filename and $mode. The $filename represents the file to be opended and $mode represents the file mode for example read-
only, read-write, write-only etc.
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.
w Opens file in write-only mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it
creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it
creates a new file.
a Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it creates a new file.
x Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. If file is found, fopen() function returns FALSE.
c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this
function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file
PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read
data line by line and read data character by character.
o fread()
o fgets()
o fgetc()
Syntax
1. string fread (resource $handle , int $length )
Example
1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>
Output
Syntax
1. string fgets ( resource $handle [, int $length ] )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>
Output
Syntax
1. string fgetc ( resource $handle )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>
Output
PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w, r+, w+, x, x+, c
or c+ mode.
Syntax
Example
1. <?php
2. $fp = fopen('data.html', 'w');//opens file in write-only mode
3. fwrite($fp, 'welcome ');
4. fwrite($fp, 'to php file write');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output: data.txt
1. <?php
2. $fp = fopen('data.html', 'w');//opens file in write-only mode
3. fwrite($fp, 'hello');
4. fclose($fp);
5.
6. echo "File written successfully";
7. ?>
Output: data.txt
hello
You can append data into file by using a or a+ mode in fopen() function. Let's see a simple example that appends data into
data.txt file.
data.txt
Example
1. <?php
2. $fp = fopen('data.html', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>
Output: data.txt
In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only: file name. It is
similar to UNIX C unlink() function.
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is deleted successfully
otherwise FALSE.
Syntax
Output
PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allow you to upload binary and text files both. Moreover, you can have the full control over the file
to be uploaded through PHP authentication and file operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type,
file size, temp file name and errors associated with file.
$_FILES['filename']['name']
$_FILES['filename']['type']
$_FILES['filename']['size']
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The move_uploaded_file() function checks
internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request.
Syntax
File: uploadform.html
1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10. ?>
PHP enables you to download file easily using built-in readfile() function. The readfile() function reads a file and writes it to
the output buffer.
$use_include_path: it is the optional parameter. It is by default false. You can set it to true to the search the file in the
included_path.
Syntax
1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
$to: specifies receiver or receivers of the mail. The receiver must be specified one of the following forms.
o [email protected]
o [email protected], [email protected]
o User <[email protected]>
o User <[email protected]>, Another User <[email protected]>
Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not be larger than 70
characters.
$additional_headers (optional): specifies the additional headers such as From, CC, BCC etc. Extra additional headers
should also be separated with CRLF ( \r\n ).
1. <?php
2. $to = "[email protected]";//change receiver address
3. $subject = "This is subject";
4. $message = "This is simple text message.";
5. $header = "From:[email protected] \r\n";
6. $result = mail ($to,$subject,$message,$header);
7.
8. if( $result == true ){
9. echo "Message sent successfully...";
10. }else{
11. echo "Sorry, unable to send mail...";
12. }
13. ?>
If you run this code on the live server, it will send an email to the specified receiver.
To send HTML message, you need to mention Content-type text/html in the message header.
1. <?php
2. $to = "[email protected]";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:[email protected] \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>
To send message with attachment, you need to mention many header information which is used in the example given below.
1. <?php
2. $to = "[email protected]";
3. $subject = "This is subject";
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("tmp/test.html", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("tmp/test.html");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert \r\n after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:[email protected]\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use one of the 2 alternatives.
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if connection is established
or null.
Syntax
1. resource mysqli_connect (server, username, password)
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if connection is closed or false.
Syntax
1. bool mysqli_close(resource $resource_link)
Output:
Connected successfully
Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Database mydb created successfully.
PHP mysql_query() function is used to create table. Since PHP 5.5, mysql_query() function is deprecated. Now it is
recommended to use one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Table emp5 created successfully
PHP mysql_query() function is used to update record in a table. Since PHP 5.5, mysql_query() function is deprecated. Now
it is recommended to use one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Record updated successfully
PHP mysql_query() function is used to delete record in a table. Since PHP 5.5, mysql_query() function is deprecated. Now
it is recommended to use one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Record deleted successfully
PHP mysql_query() function is used to execute select query with order by clause. Since PHP 5.5, mysql_query() function
is deprecated. Now it is recommended to use one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
The order by clause is used to fetch data in ascending order or descending order on the basis of column.
Let's see the query to select data from emp4 table in ascending order on the basis of name column.
Let's see the query to select data from emp4 table in descending order on the basis of name column.
Output:
Connected successfully
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :1
Chapter Four
Object Oriented Concepts
Before we go in detail, lets define important terms related to Object Oriented Programming.
Class − This is a programmer-defined data type, which includes local functions as well as local data. You
can think of a class as a template for making many instances of the same kind (or class) of object.
Object − An individual instance of the data structure defined by a class. You define a class once and then
make many objects that belong to it. Objects are also known as instance.
Member Variable − These are the variables defined inside a class. This data will be invisible to the outside
of the class and can be accessed via member functions. These variables are called attribute of the object
once an object is created.
Member function − These are the function defined inside a class and are used to access object data.
Inheritance − When a class is defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and variables of a parent class.
Parent class − A class that is inherited from by another class. This is also called a base class or super class.
Child Class − A class that inherits from another class. This is also called a subclass or derived class.
Polymorphism − This is an object oriented concept where same function can be used for different
purposes. For example function name will remain same but it make take different number of arguments and
can do different task.
Overloading − a type of polymorphism in which some or all of operators have different implementations
depending on the types of their arguments. Similarly functions can also be overloaded with different
implementation.
Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).
Encapsulation − refers to a concept where we encapsulate all the data and member functions together to
form an object.
Constructor − refers to a special type of function which will be called automatically whenever there is an
object formation from a class.
Destructor − refers to a special type of function which will be called automatically whenever an object is
deleted or goes out of scope.
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
The special form class, followed by the name of the class that you want to define.
A set of braces enclosing any number of variable declarations and function definitions.
Variable declarations start with the special form var, which is followed by a conventional $ variable name;
they may also have an initial assignment to a constant value.
Function definitions look much like standalone PHP functions but are local to the class and will be used to
set and access object data.
Example
Here is an example which defines a class of Books type −
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Here we have created three objects and these objects are independent of each other and they
will have their existence separately. Next we will see how to access member function and
process member variables.
Following example shows how to set title and prices for the three books by calling member
functions.
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example −
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Constructor Functions
Constructor Functions are special type of functions which are called automatically whenever
an object is created. So we take full advantage of this behaviour, by initializing many things
through constructor functions.
PHP provides a special function called __construct() to define a constructor. You can pass
as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and
title for the book at the time of object creation.
Now we don't need to call set function separately to set price and title. We can initialize
these two member variables at the time of object creation only. Check following example
below −
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Destructor
Like a constructor function you can define a destructor function using function __destruct().
You can release all the resources with-in a destructor.
Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the
extends clause. The syntax is as follows −
The effect of inheritance is that the child class (or subclass or derived class) has the
following characteristics −
Automatically has all the member variable declarations of the parent class.
Automatically has all the same member functions as the parent, which (by default) will work the same way
as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the
requirement.
function setPublisher($par){
$this->publisher = $par;
}
function getPublisher(){
echo $this->publisher. "<br />";
}
}
Now apart from inherited functions, class Novel keeps two additional member functions.
Function Overriding
Function definitions in child classes override definitions with the same name in parent
classes. In a child class, we can modify the definition of a function inherited from parent
class.
In the following example getPrice and getTitle functions are overridden to return some
values.
function getPrice() {
echo $this->price . "<br/>";
return $this->price;
}
function getTitle(){
echo $this->title . "<br/>";
return $this->title;
}
Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to say,
they may be accessed in three possible situations −
From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility
of the members of a class then you define class members as private or protected.
Private members
By designating a member private, you limit its accessibility to the class in which it is
declared. The private member cannot be referred to from classes that inherit the class in
which it is declared and cannot be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
private $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
function myPublicFunction() {
return("I'm visible!");
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be
visible, as will $driver. The extending class will not have any awareness of or access to
myPrivateFunction and $car, because they are declared private.
Protected members
A protected property or method is accessible in the class in which it is declared, as well as in
classes that extend that class. Protected members are not available outside of those two kinds
of classes. A class member can be made protected by using protected keyword in front of
the member.
class MyClass {
protected $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
}
}
Interfaces
Interfaces are defined to provide a common function names to the implementers. Different
implementors can implement those interfaces according to their requirements. You can say,
interfaces are skeletons which are implemented by developers.
interface Mail {
public function sendMail();
}
Constants
A constant is somewhat like a variable, in that it holds a value, but is really more like a
function because a constant is immutable. Once you declare a constant, it does not change.
class MyClass {
const requiredMargin = 1.7;
function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}
In this class, requiredMargin is a constant. It is declared with the keyword const, and under
no circumstances can it be changed to anything other than 1.7. Note that the constant's name
does not have a leading $, as variable names do.
Abstract Classes
An abstract class is one that cannot be instantiated, only inherited. You declare an abstract
class with the keyword abstract, like this −
When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child; additionally, these methods must be defined with
the same visibility.
Note that function definitions inside an abstract class must also be preceded by the keyword
abstract. It is not legal to have abstract function definitions inside a non-abstract class.
Static Keyword
Declaring class members or methods as static makes them accessible without needing an
instantiation of the class. A member declared as static can not be accessed with an
instantiated class object (though a static method can).
<?php
class Foo {
public static $my_static = 'foo';
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method
by prefixing the definition with final. If the class itself is being defined final then it cannot
be extended.
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}
class Name {
var $_firstName;
var $_lastName;
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name {
var $_middleInitial;
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
function toString() {
return(Name::toString() . " " . $this->_middleInitial);
}
}
In this example, we have a parent class (Name), which has a two-argument constructor, and
a subclass (NameSub1), which has a three-argument constructor. The constructor of
NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing
two of its arguments along) and then setting an additional field. Similarly, NameSub1
defines its non constructor toString() function in terms of the parent function that it
overrides.
NOTE − A constructor can be defined with the same name as the name of a class. It is
defined in above example.
Glossary
PHP 5 MySQLi Functions
The mysqli functions are designed to communicate with MySQL 4.1 or later.
Using the mysqli functions you can take advantage of all the latest and advanced features of MySQL, which you may not be
able to do with the earlier MySQL functions. However the MySQLi functions are available only with PHP 5 or later.
Function Description
Function Description
Function Description
Function Description
Function Description
cal_days_in_month() Returns the number of days in a month for a specified year and
calendar
cal_from_jd() Converts a Julian Day Count into a date of the specified calendar
cal_info() Returns information about a specified calendar
cal_to_jd() Converts a date in a specified calendar to Julian Day Count
easter_date() Returns the Unix timestamp for midnight on Easter of the given year
easter_days() Returns the number of days after March 21 on which Easter falls for a
given year
frenchtojd() Converts a date from the French Republican Calendar to a Julian Day
Count
gregoriantojd() Converts a Gregorian date to a Julian Day Count
jddayofweek() Returns the day of the week
jdmonthname() Returns a month name
jdtofrench() Converts a Julian Day Count to a French Republican date
jdtogregorian() Converts Julian Day Count to Gregorian date
jdtojewish() Converts a Julian day count to a Jewish calendar date
jdtojulian() Converts a Julian Day Count to a Julian Calendar Date
jdtounix() Convert Julian Day to Unix timestamp
jewishtojd() Converts a date in the Jewish Calendar to Julian Day Count