• PHP was first coded by Rasmus Lerdorf, an IT contractor, tracking his own clients.
  • It was known as Personal Home Page, written using pearl script.
  • In 1996, PHP-FI(Form Interpreter) was released seeing the popularity and inflowing enquiries.
  • In 1998 PHP 3 was released and updated to PHP 4 later on.


  • Speed: it uses very less resources.
  • Stability : because it has cross browser compatibility in terms of Operating system platform and also different server and database technologies
  • Ease of usage:  There is no need of any prior knowledge of programming, only basic knowledge in HTML is enough to handle PHP.

Working of PHP

  • As Javascript is between server code(file/program) and the user (browser), the PHP is between the Server and the Database.
  • The PHP will parse the users code(HTML/Browser) on behalf of Web server and communicate with the database.
  • It is known as server side coding/technology.
  • It is not by itself a server but it is build as an “add on”(extra programming/parsing technique) to help the web server.  This is the reason why it is a light weight component and has good speed.
  • PHP works with server and also database.  It is more specific to database and server techniques.  The communication between website users and database becomes easy with PHP coding.
  • It works on varied platforms of windows and linux. 
  • It works with most of the servers available in market.
  • It works with most of the database systems also.
  • The most favoured are “Linux” “Apache server”, “My SQL” with “PHP”(LAMP).  Since these are open source codes, which are freely available for download on the net, it has taken the popularity by storm.  It accounts to 56% of web servers using PHP.

Important NOTE:

  • Wamp Server is a collection of My SQL, Apache, PHP loaded on network server by name “phpserver”.
  • Open the browser and type //phpserver/php/apt108  in the address bar.
  • Create a folder on your name/reg number and save your files in that.
  • To see the output of your files double click on the file you saved, after coding it, from the same directory in the browser.
  • This means that the file you are saving is saved on the server which is going to be used by the user when connected.  So when you double click the file you are opening as a user in the browser.
  • If using dreamweaver also, give the same directory when asked to save the file.  It should look something like “//phpserver/php/apt108/B555”
  • Open the dreamweaver and click on “PHP” to open a new file.  Save the file after coding without any extension.  The extension “php” will automatically allotted by dreamweaver.
  • Click on browser while saving and point towards “Mynetwork – Entire network – Microsoft windows network – Aptech – PHPSERVER(phpserver) – www – PHP –  Apt108 “ and enter the folder you have created the name with.

Basics of PHP

  • PHP is not case sensitive. echo, Echo, ECHO are same.
  • It is a loosely typed language. For example when PHP pharser sees the character $ it expects an variable/any object.  So you can mix the variable with all other text as simply writing English language.
  • A PHP statement is a command for browser.
  • Use semicolon (;) at the end of each statement, it confirms the end of one command like a full stop for english language.
  • Using ; you can write more commands in a single line.
  • “{“ and “}” are used to create one single block of commands to ensure that all the executed.
  • PHP code is embedded anywhere inside HTML file with any one tag style given below.
  • <?php  Code for php?>
  • <?php Code for ?>
  • <script language=”php”> code for php </script>
  • Comments in PHP are given with “//” or “#” for single line and /* and */ for multi line comments.


Ex.      <html>
//saying hello
<?php echo(“<h1> Hello world </H>”); ?>
# even this is single line comment in php.
echo command is used more often to display the text on the users browser. There is no hard and fast rule to concatenate strings you can just type the $ symbol for any variable inside the text itself.

Adding Dynamic content
You can use all html tags inside the text while displaying using the echo() function.  This will result in producing dynamically an HTML webpage. Ex. Echo(“<h1> hello </h1>”);

Escape Sequence

  • Escape sequence is a series of characters followed by a “\” (back slash).
  • It gives instructions to the PHP pharser that it is a special symbol following the slash.

Ex. Escape sequence
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Escape Sequence</title>
<?php echo ("<textarea rows=5 cols=54>");
echo ("\"this is a textarea created dynamically using the php echo command");
echo ("you will be finding this line broken into two pieces from here \n and ");
echo("you will see that tabs are also functionings \t\t\t\t\t properly ");
echo("this is closing the textarea </textarea>");

Reserved Words
Reserved words are words reserved for the system to use.  These words are not to be used by the user for naming either variables, functions etc.










































































  • Variable stores a reference to the location of the memory. 
  • It can hold any value of a given type.
  • Every variable should start with “$” symbol.
  • You can use numbers, alphabets and Underscore (“_“) for naming a variable.
  • Variable name should not begin with number.
  • While using the variables, PHP automatically sets the type of variable itself.
  • Variable names are case sensitive. ie, $name, $Name and $NAME is different.


Ex.      $abc

  • Values are assigned using the “=” operator.
  • Every statement should end with a semicolon.
  • A variable once declared can hold any type of data there is no restriction on the type of data values.

Basic data types are :-

  • Floating type: these data types have a number with a decimal value ie., 3.142, 4.555 etc.
  • Integer type : these data types are numbers without any decimal value. ie integer like 234, 456, 58777.

(c) Strings are values of text embedded inside quotes like “my name”, ‘who’ etc.
(d) Boolean values carry either “true” or “false”.
(e) Null means empty/no value. (null is case insensitive).


Ex.Data types
<?php $str = “here is a string”, $non=NULL;
$int=77;  $flt = 3.142;
echo(“Floating- point : $flt<br>”);


  • Functions are small set of programme codes/statements used to execute a certain task whenever called.
  • They do not execute unless called.
  • Names of functions should be same as names of variables.
  • Two types of functions are found in PHP (a) inbuild like “echo()” (b) User defined.
  • A function should be written with keyword “function” followed by a space and a name.  Followed by a pair of parenthesis.  Then by a pair of curly braces “{}”, in which the code to be executed is enclosed.  Ex. function go() { echo(“<br>”);}
  • Functions should be defined( ie., code should be written) before we call the function.
  • While calling a function use the name followed by a pair of parenthesis. Ex. go();

<html><head><title>functions demo</title></body>
<?php function go(){
}  ?>
<?php go();?>
<p>**** HTML is great for static content ****<p>
<?php go();?>

Passing values to functions

  • The values are passed to the function by writing them within the braces while calling.
  • They should be seperated by a comma.
  • These are called as arguments.
  • There is no restriction on number of arguments to send, but the serial of values should match.  When we call the function, the series of arguments used, should match the function which is receiving the arument series.


Ex. go(‘hello”, “ramesh”); is calling; and function go(“greeting”, “name”) is receiving the first argument is received properly.  If you alter to go(“ramesh”, “hello”) there will be a problem because the function is expecting greeting first and not the name.

  • You can pass values or even variables inside the brackets while calling the functions.
  • A php file may have any number of functions inside it.
  • A call can be made from any code to a function.
  • Function can also call another function from within it.
  • All the functions can be called any number of times.


Ex. Multiple functions
<? Php
function make_double($num){
$new_number = twice($num);
echo (“The value is $new_number”);
function twice($arg){
return $arg + $arg;

<html><head><title>Multiple functions </title></head><body>
<h3> <?php make_double(4);  ?> </h3>

Variable Scope

  • Variables carry certain value.  These values are not available wherever you need for usage.  But are available within the scope you declare.
  • A “scope” means the area of the program when the value will be accessible. 
  • Generally the scope would be the place inside the curley braces “{ }”.
  • If the variable is  declared within the function then the variable will be known only to the function.  Outside the function the variable is not known.  Then this is said to be the local variable for the function.
  • If the variable is declared outside the function, then that variable value can be used by all the functions and code outside the function.  This is called a global variable.
  • If the code is trying to access the variable even before its creation then there would be a error.
  • The code or functions can access the variable only after the declaration/creation.
  • Global variables are created with simple declarations but while addressing them from inside a function they have to be re-declared before using them, with the key word “global”.
  • It is always a good practice to place all the functions and variables of the PHP before even starting the HTML code.  It signals a clean coding system.


Ex. Variable scope
<?php $num;
function make_triple($arg){
global $num;
$num = $arg + $arg + $arg:

function thrice(){
global $num;
echo(“the value is $num”);
<html><head><title>variable scope</title></head>
<body> <h3><?php make_triple(4); ?>

Multiple Arguments

  • You can provide multiple arguments for the function by separating them with a comma.
  • In PHP you can also provide a default value to the arguments right inside the receiving parenthesis.
  • If the argument is received with a value then this default value is overwritten else the default value is taken into consideration.


Ex. function multiply($a=45, $b=50).
This function will receive two arguments as its parameters if the values are received they will be assigned to a and b.  Otherwise a will be assigned with 45 and b with 50.

  • Note that giving default value is optional and not compulsory.  These values are given so that you don’t have any runtime error in the code.

Arithmetical operators
For performing mathematical operations on the values we a set of operators.




Basic Arithmetic Operators



$a=15, $b=10,
$c = $a+$b;




$c = $a-$b;












$c= $a%$b; results in 5.

Gives the remainder after division.


Increments the operand with 1.

$a=15, $b=10
$a++;  $c=($a++)-$b =5;
++$a;  $c=(++$a)-$b =6;

$a++ results in operation first and increment next.
++$a results in increment first and operation next.


decreases the operand with 1.

$a=15, $b=10
$a--;  $c=($a--)-$b =5;
--$a;  $c=(--$a)-$b =6;

$a—results in operation
first and increment next.
--$a results in increment
first ad operation next.

  • All *, -, /,+ will work perfectly as you expected.
  • “.” (dot) is used for concatenating two strings/values/variables and produce a single string.




Ex. Arithematic Operators
$addnum = 20+3;
$addstr="php is "."just like java script";
$sub=35.75 - 28.25;
$mul= 8* 50;
$mod= 67%2;
$inc=5; $inc=++$inc;
$dec = 5; $dec = --$dec;

$result = "addnum: $addnum <br>";
$result.= "addstr: $addstr <br>";
$result.= "sub : $sub <br>";
$result.= "mul: $mul <br>";
$result.= "mod: $mod <br>";
$result.= "inc : $inc <br>";
$result.= "dec : $dec <br>";
<head> <title>arithmetical operators</title></head>
<h2><?php echo ($result) ; ?></h2>


Ex.Using Unary Operator
<SCRIPT language="php">
echo("<h1>The given number is :$no</h1>");
echo("<h2> $no operated with ++ gives :".(++$no));
echo("<p>".(--$no)." operated with -- gives :".(--$no));
echo("<p>negation of $no is ". -(no));

Logical operators



Returns true when both the operands are true
Can use both “&&” or “and”.

$a=10, $b=15;

if($a>10 &&$b>10) $c=20;
results in $c=null.

if($b>10) $c=$b;
results in $c=15



Returns true when either operand is true
Can use both “||” or “or”.

if($a>10 || $b>10) $c=20;
results in $c=20;


Logical exclusive XOR. Only one condition should be true, then the result will be true else false.

if($a>10 xor $b>10) $c=20;
results in $c=20;
(because only second condition is true).


Returns true if operand is false and false if operand is true.

$a=true; $b=false;
if($a) $c=40 results in $c=40;
if(!$b) $c=50 results in $c=50;

  • Logical operators are used only with expressions which can evolve into a true or false or with boolean type of data.
  • && and “and” operator are one and same.  These operators result into true if both the conditions are true and result into false even if one operand is false.
  • “&&/and” operators are useful when we want to take a decision path if two conditions are true.
  • || and “or” are one and same.  You can use any of them.  When used these operators result in true if atleast one of the condition is true, and results in false if both the conditions are false.
  • “||, or” operator in php is useful when we want to take a decision path based on atleast one condition is true from two.
  • “xor” will result in true only if one of the condition is true.  Even if two conditions are true, it results in false.
  • “xor” is useful when we want to take decision based on two conditions out of which only one should be true while other being false.
  • “!” Logical not operator results in opposite of what the condition is.  If condition is true it results in false, if the condition is false it results in true.
  • “!” logical not works like a toggle(on/off) when we want to use in a loop, by changing the value to true and false alternatively.

Ex. Logical Operators
$c = false;

if($a>45 && $b<100) echo("Result of addition is : ".($a+$b)."<br>");
if($b<50 and $b==66) echo("This may not be printed");
if($a==50 or $b<10) echo("This is passing the test because one condition is true <br>");
if($a<100 || $b<10) echo("This also passed the test because one condition is true <br>");
if(!$c) echo("Result of logical not<br>");
if($a<100 XOR $b<10) echo("This is the result of exclusive or<br>");


Ex. Logical Operators
$a=true; $b=false;

# test both operands for true
$test1 = ($a and $a)? "true" : "false";
$test2 = ($a and $b)? "true" : "false";
$test3 = ($b and $b)? "true" : "false";

# test either operand for true
$test4 = ($a or $a)? "true" : "false";
$test5 = ($a or $b)? "true" : "false";
$test6 = ($b or $b)? "true" : "false";

#test for single operand is true
$test7 = ($a xor $a)? "true" : "false";
$test8 = ($a xor $b)? "true" : "false";
$test9 = ($b xor $b)? "true" : "false";

#invert values
$test10 = (!$a)? "true" : "false";
$test11 = (!$b)? "true" : "false";

$result = "AND -1:$test1 2:$test2 3:$test3<br>";
$result .= "OR -1:$test4 2:$test5 3:$test6<br>";
$result .= "XOR -1:$test7 2:$test8 3:$test9<br>";
$result .= "NOT -1:$test10 2:$test11<br>";
<?PHP ECHO($result); ?>

Assignment Operators

  • The “=” operator assigns the value to the left hand side with the value equal to the right hand side. It is not checking for equality of two values.
  • For rest of the assignment operators we have the read the expressions as “The new value of left side is the old value of it plus/multiply/divide/minus the given value on the right hand side.

Assignment Operators


Number on the right side is assigned to left side.

$a=15; $ b=10;
$a = $b; results in $a=10;
$a = ($b*100)/10 results in $a=100;


New value of left side will be old value of it minus the number on right side.

$a=$15; b=10
$a-=4; results in (15-4) $a=11;
$b-=2; results in (10-2) $b=8;

(for numbers)

New value of left side will be old value of it plus the number on right side.

$a=15; $b=10
$a+=$b; results in (15+10) $a=25;
$b+=2; results in (10+2) $b=12;


New value of left side will be old value of it divided with the number on right side.

$a=15; $b=10
$a /= 2; results in (15 / 2) $a=7.5;
$b /= 2; results in (10 / 2) $b=5;


New value of left side will be old value of it modulus with the number  on right side.

$a=15; $b=10
$a %= 3; remainder of (15 / 3) $a=0;
$b %= 3; remainder of (10 / 3) $b=1;


New value of left side will be old value of it multiplied with the number on right side.

$a=15; $b=2;
$a*=2; results in 30
$b*=4l; results in 8


New value of left side string will be equal to old value of it appended with the new string on the right.

$a=”this is”;
result in $a=”This is text”


Ex. Assignment Operators
$a = "php "; $aa = "script" ; $storea=$a;

$b=8; $bb = 4; $storeb=$b;

$c = 7.5; $cc = 2.25; $storec=$c;
$c -=$cc;

$d = 8; $dd = 4; $stored=$d;
$d *= $dd;

$e = 8; $ee=4; $storee=$e;
$e /= $ee;

$f = 8; $ff = 3; $storef=$f;
$f %= $ff;

$result = "\"$storea \" add and assigned with string \"$aa\" is : $a<br>";
$result .= "\n $storeb added and assigned with interger $bb is : $b <br>";
$result .= "\n $storec substracted and assigned wth float $cc is : $c<br>";
$result .= "\n $stored multiplied and assigned with $dd is : $d<br>";
$result .= "\n $storee divided and asigned with $ee is : $e<br>";
$result .= "\n $storef modulo and assign with $ff is : $f";

<html><head><title> assignment operators </title></head>
<body> <?php echo($result); ?> </body></html>

Comparison Operators




Returns true if operands are equal

$a=10; $b=15
if($a==$b) $c=14; result $c=null;
$a=10; $b=10
if($a==$b) $c=14; result $c=14;


Returns true if operands are not equal

$a=15; $b=24;
if($a!=$b) $c=12; result $c=12;
$a=15; $b=15;
if($a!=$b) $c=12; result $c=null

Returns true if left operand is greater than right operand.

$a=10, $b=10;
$a>$b //result false;
$b>$a //result false;

Returns true if left operand is less than right operand.

$a=19, $b=23;
$a<$b //result true;
$b<$a //result false;


Returns true if left operand is greater than or equal to right operand.

$a=14, $b=14;
$a>=$b //result true;
$a=14, $b=16;
$b>= $a //result true;


Returns true if left operan is less than or equal to right.

$a=213, $b=234;
$a<=$b result true;
$a=313, $b=313;
$a<=$b result true;

  • Note that “=” is used for assignment of a value to a variable but “==” is used to compare two values.
  • “==” results in either true or false based on the types of the values.
  • “==” results in true if two numbers are equal.
  • “==” results in true if two strings contain same characters in same positions.
  • “!=” (not equal to) results in true if two number/strings are not equal in some manner, if they are equal this operator will return false.
  • “>” (greater than) results in true if the left hand side is greater in value when compared to the right hand side. 
  • Note that expressions like (a+b), (23+34) etc., can also be used in the place of variables/values.
  • “<” (lesser than) equals to true if the left hand side is lesser than the right hand side in value.
  • Note that strings cannot be compared using “<” ,  “>”, “<=”,”>=” operators.
  • “<=” (lesser than or equal to)  if the left side is equal to right side or lesser than the right hand side then this operator will result in “true” else it will result in false.
  • “>=” (greater than or equal to) if the left side is equal or greater than the right hand side then this operator will result in true else it will result in false.


Ex. Comparison operators
$a = ("php" == "php")? "true" : "false";
$b = ("php" == "PHP")? "true" : "false";

     $c = (1.758 == 1.758)? "true" : "false";
$d = (5 != 5 )? "true" : "false";

$e = (true == true)? "true" : "false";
$f = (false != false)? "true" : "false";

$g = (100 < 100 )? "true" : "false";
$h = (100 < 200)? "true" : "false";

$i = (100 <= 100 )? "true" : "false";
$j = ( -1 > 1 )? "true" : "false";

$result = "Test Strings \$a:$a  \$b:$b<br>";
$result .= "Test Numbers \$c:$c \$d:$d<br>";
$result .= "Test Boolean \$e:$e \$f:$f<br>";
$result .= "Test Less Than \$g:$g \$h:$h<br>";
$result .= "Test Greater Than Or Equal \$i:$i <br>";
$result .= "Test Greater Than \$j:4j";
<html><head><title>Comparison Operators </title></head>
<?php echo ("<h2>$result</h2>"); ?>

Conditional Operator

  • SYNTAX: (condition) ? if true do this : if false do this;
  • First the condition is evaluated and if it results in true the first statement is executed and if it is false the second condition is executed.
  • Generally, this operator is used to assign a value or take a function based on a decision.


Ex. Conditional Operator

function is_odd(){
global $num;
echo ("$num is an odd number <hr> ");

function is_even(){
global $num;
echo ("$num is an even number <hr>");

<html><head><title>Conditional operator </title></head>
($num % 2 != 0) ? is_odd() : is_even();

$num = 44;
($num %2 !=  0 ) ? is_odd() : is_even();

If conditional statement

  • Syntax: if(test expression) statement to execute when true else statement to excute for default.
  • First the condition is evaluated.  If the condition is true the immediate statement/s executed.
  • The “else” clause is executed if the condition is false or as default.
  • “test expression” can comprise of number, strings expressions or variable comparisons but the end result should be either true or false.
  • If there is no more than one statement there is no need of any parenthesis.
  • If there are more than one statmement to be executed then they should be kept in curly braces. “{ }”.


Ex. If Statement
<head><title> if statment </title></head>
$num = 7;
if ($num % 2 != 0){
$msg = "$num is an odd number .";
echo ($msg);          

“If else” statement (conditional branching)

  • Syntax : if(test expression) do this; else do this;
  • First the condition in the first “if” is evaluated if its true the statements following the condition are executed.
  • Else next if codition is tested.
  • Several conditions are tested until you reach a true expression.
  • If no condition is found true it ignores the rest of the code.
  • If an else clause is mentioned then it is executed by default.
  • This is also known as “if else ladder”.


Ex. If else statement
<html><head><title>If-else Statement</title></head>
$num=2;  $bool=false;
if($num == 1  and  $bool == true)  echo("Test  1 success")  ;
if($num == 2  and  $bool == true)  echo("Test  2 success")  ;
if($num == 2  and  $bool == false)  echo("Test  3 success")  ;
if($num == 3  and  $bool == false)  echo("Test  4 success")  ;

“Switch” statement
case 1:
  execute code block 1
case 2:
  execute code block 2
  code to be executed if n is different from case 1 and 2

  • Expression n (most often a variable) is evaluated once. The value is then compared with the values for each “case” in the structure. If there is a match, the block of code associated with that case is executed.
  • Use “break” to prevent the code from running into the next case automatically.


Ex:  switch (no){
Case 1:
Case 2:
Case 3:
Case 4: echo (“all options are contained till 4 in this statement”);

  • If you need to execute a single set of statement/s for two or more consecutive options.  avoid break statement as given above.
  • You can use any type of data inside the “switch()” like numbers, strings, boolean.
  • You can also use expressions which will result in one value.


Ex. Switch statement
<html><head><title>switch Statement</title></head>


case 1: echo("This is case 1 code")  ;

                   case 2: echo("This is case 2 code")  ;

                   case 3: echo("This is case 3 code")  ;

default :echo("This is default code")  ;

“for” loop

  • Syntax : for (initialization ; test condition; iteration) { statement/s}
  • First the initialization section will initialize the variable.
  • Then the “test condition” is tested.
  • If the condition is true the statement/s following are executed.
  • Next, the condition is checked, if its true the statements are executed again and in the iteration section the value is either incremented or decremented.
  • This process is repeated till the condition becomes false.
  • “for” loop should be used if you know the number of times you want to execute a given code.
  • You can initialize multiple variables at a time inside the for loop.  But commas(,) should be should be used between them.
  • You can also use multiple variables in iteration section separated by a comma.


Ex. For Loop
<html><head><title>switch Statement</title></head>
$a=0; $b=0;

          for($i=0; $i<5; $i++){
$a += 10; $b +=5;
echo("at the end of the loop a=$a and b=$b");

While loop

  • Syntax:  while (test condition){


  • First the test condition is tested, if its true the code inside the curly braces is executed else not executed.
  • Test condition can be any expression but it should evaluate into a “true” or “false”.
  • The loop will continue unless the condition is broken from inside the code.  So the code inside should ensure that the condition will become false at some point. Otherwise the loop will become infinite loop.
  • This loop should be used when there is a situation where we do not know how many times the loop should be executed to achieve a target.
  • Note that if the condition is false the loop will not execute even once.


Ex. While loop
<html><head><title> If  Statement</title></head>
$num = 0; $i=50;

while ( $num < 10){
echo( "loop stopped at $num \$i is now $i"  );


Do while loop

  • Syntax : do {

} while (test condition)

  • Firs the set of commands/statements given in the block are executed and then the condition is tested.
  • If the condition results in true the statements will be executed again else the loop will stop.
  • “do while”  loop construct should be used when you need some information to be executed before taking the decision. And when we do not know the number of times we are going to execute the loop for a search.


Ex. Do while statement
<head><title>do while  loop </title></head>
$i=0; $num=50;
do {$num = 50; $i++;}
echo (“loop stopped at $i<br/> \$num is now $ num”);

Breaking loops

  • It is not necessary that the loop has to complete unless the condition is complete.  We can even break the loop based on certain condition.
  • The condition for break should be mentioned within the block of the loop.
  • A simple “break” statement followed by a semicolon will break the loop at any point inside the loop block.
  • Generally the break statement will be accompanied with a “if” condition.

Ex.Break statement
<html><head><title> Break statement</title></head>
While ($i<6){
if($i == 3) break;
Echo (“loop stopped at $i by break statement”);

Continue Statement

  • The continue statement is used to “bypass” certain code under a given situation and go ahead with the next iteration.
  • First give a “if” statement and test for the given condition and use “continue” statement to bypass the rest of the code written in the block of the loop.
  • It will go ahead with the next iteration.


Ex. Continue statement
<html><head><title>continue statement</title></head>
$i = 0; $passes;
if($i<5) continue;
$passes .=”$i “;

echo(“loop stopped at $i<br>”);
echo(“completed iterations : $passes”);

“return” statement

  • The “return” statement is used within a function to return the values to the calling statement.
  • Only one value can be returned from any function.


Ex. Return statement
function multiply ($a=1, $b=1, $c=1, $d=1, $e=1){

$total = $a * ($b * ($c * ($d * $e)));
Return $total;

<html><head><title>return statement <title></head>
Each year has 3651/4 days <br/>
Each day has 24 hours <br/>
Each hour has 60 minutes <br/>
Each year has <?php echo (multiply (365.25, 24, 24, 60)) ?>


  • An array can be defined as a single variable containing many values.
  • In php an array can contain different types of data in one single array. There is no restriction of type of data unlike in java script etc.  A single array can hold different types of data in itself.
  • There are three basic types of arrays in PHP.
  • Numeric Array – Array with a numeric ID key.
  • Associative Array – Array where each ID is associated with a value.
  • Multi-dimensional Array – Array containing one or more arrays in it.


Numeric Array

  • Numeric IDs are automatically assigned to the array.
  • All the values can be addressed using an index number. Ex. $a[3], $myarr[0] …
  • The index value starts from 0.
  • All the values can be assigned while declaring the array itself.


Ex.      $subjects = array(“English”, “Maths”, “Science”, “Social”);
$marks = array(45, 65, 66, 76, 78);

  • elements of the array should be seperated with a comma.
  • An array containing 5 elements will have index values from 0 – 4.
  • The last element may be addressed as $marks[4].
  • While giving the index numbers square brackets”[ ]” should be used.
  • Values can also be assigned using individual index numbers.


Ex. $subjects[0] = “english” ;
$subjects[1] = “Maths” ;
$subjects[2] = “science” ;
$subjects[3] = “social” ;

  • Individual values can be used as we use normal variables.


Ex. echo $subjects[0].” is the first language and ”.$subjects[1].” ,”.$subjects[2].” , “. $subjects[3].” are compulsory subjects” ;

english is the first language and Maths, science, social are compulsory      subjects.

  • If you need to use the index values from 1 instead of 0 you can do so by inserting  “1=>” inside the array before the first element, while assigning the values.


Ex. $subjects = array(1=> ”english”, “maths”, “science”, “social”);
Now $subjects[1] will cause the result as “english” and there is no element like


Ex. using arrays
$dy = array("19th ", "20th ", "7th ");
$mo = array("Aug ", "Aug ", "Feb ");
$yr = array("1979 ", "2009", "1973 ");

echo ($dy[0].$mo[0].$yr[0]."<br>");
echo ($dy[1].$mo[1].$yr[1]."<br>");
echo ($dy[2].$mo[2].$yr[2]."<br>");

  • An php array can contain different types of data items in a single array.
  • Array can also change values after assigned to the array variable.
  • These feature are demonstrated in the following example.

Associative Arrays

  • Associative arrays have values and keys assigned to it. 
  • There is no id assigned to it  automatically by the system, instead we have to assign key and value both.


Ex. $marks=array(“Ram” => 456, “sham”=>396, “rajesh”=>512, “ramesh”=>443);

  • The key and value can be of any data types.  But each value is associated with its key.
  • In the above example the names of the students are keys and the values are the marks held by the array.
  • “ => ” is used to associate the values with the keys.
  • For addressing individual marks we have to use $marks[‘Ram’].  This will produce the value of 456 which is associated with it.
  • Note that the id here is ‘Ram’ which is enclosed in single quotes.  Though there is no hard rule that we have to use single or double quotes for ids within the square brackets, it is a convention to use single quotes, to differentiate between strings and ids.
  • The key string used in above example is case sensitive because data type is of string.


Ex. $marks[‘ram’] will not give result.
$marks[‘Ram’] will give the result of 456.

  • You can also use the individual values as we use variables.


Ex. echo (“ram and sham together scored “.($marks[‘Ram’]+$marks[‘sham’]) );


NOTE: Remember that since the associative array are having its own keys we cannot use the for loop for displaying the results.  You have evaluate your own technique to display the elements.

Multidimentional Arrays

  • In this type of arrays the array element can contain another in itself as an element.
  • Even the sub element of the array can contain another array.  Rest of the conditions for forming the arrays are same.  There is no restriction on the type of the data it contains.


Ex. changing data types

<html><head><title>changing data types in arrays</title></head>
#create an array containing 3 strings
$arr = array("red ", "green ", "blue ");

echo ("<h3>String Array before changes </h3><br>");
echo ($arr[0].$arr[1].$arr[2]."<br>");

#assign new numeric values of different data types
$arr[0] = 44;
$arr[1] = 12.5;
$arr[2] = $arr[0] + $arr[1];

echo("<h3>After changing String array to numeric array </h3><br>");
echo ("$arr[0] + $arr[1] = $arr[2]");


Note that the “+” symbol in the above example is printed as it is on the screen.

Using foreach() function

  • foreach() function in php is used to list the items of the array in sequence.
  • syntax : foreach(arr as var) {current value}
  • This is a loop just like “for loop” which will execute only that many times as the elements in the array.  There is no necessity of initialization or increment or condition. -
  • “arr” is the array from which we are extracting the elements.
  • “var” is the variable in which the elements are assigned one by one each time the loop is executed.
  • The value of the variable can be used within the curly braces with the current value.


Ex. using foreach
<html><head><title>using foreach loop</title></head>
$arr = array("red ", "green ", "blue ", "cyan", "magenta", "black", "yellow");

          foreach($arr as $value){
echo ("<li> Do you like $value?");

Finding size of arrays

  • size of the array can be found with sizeof() and count() functions.
  • Both the functions take the array as the argument inside the brackets.


Ex. finding size of arrays
<html><head><title>finding size of arrays</title></head>

$arr = array();

#assign three elements
for($i=0; $i<3; $i++){
$arr[$i] = "<li>this is element $i";

foreach($arr as $value){
echo ($value);

#assign the number of array elements
$size = count($arr);
echo ("<li> total number of elements found using \"count\" function is $size");
$size = sizeof($arr);
echo ("<li> total number of elements found using \"sizeof\" function is $size");


Inbuilt Array  functions


array_unshift :

  • Syntax :  array_unshift(array, element1, element2 ……elementn);
  • This function adds elements at the beginning of the array. 
  • It takes minimum two arguments. 
  • The first element is the array in which the element is to be set. 
  • And the second and next elements are the values to be inserted into the given array. 


array_push :

  • Synntax : array_push(array, element1, element2 ……elementn);
  • This function is same as array_unshift, but inserts elements at the end of the array. 
  • The first argument is the array in which the elements are to be inserted and the second and next arguments are meant for elements which are to be inserted into the given array.


Ex. Inserting elements
<title>inserting elements in array</title>
$arr = array("red", "green", "blue");

echo("<h2>Before modifying the array</h2><br>");
foreach($arr as $colorname){

#add elemetns at begininig of the the array
array_unshift($arr, "cyan", "magenta");

#add elements at ending of the array
array_push($arr, "yellow", "maroon");

echo("<h2>After adding elements to the array</h2><br>");
foreach($arr as $colorname){



  • Syntax :  array_shift(arrayname).
  • This function takes one array as its argument and returns the extracted element from the starting point of the element.
  • Only one element is derived.  You have to save the element in other variable.
  • After deriving the element the element is lost permanently from the given array.


  • Syntax :  array_pop(arrayname).
  • This function takes one argument, ie the name of the array from which you need to extract one element from the ending point.
  • You have to save the element in your own variable.
  • After deriving the element the element is lost permanently from the given array.


  • Syntax :  sort(arrayname).
  • This function takes one array as its argument and sorts the contents in ascending order.
  • When sorting is complete first the values with alphabets is sorted and values starting with numbers is sorted after alphabets. (alphabets first and numbers next).
  • When associative arrays are used with this function sort() will sort according to the values of the arrays and not index.
  • While sorting if multidimentional array, associative array and normal values are combined together as elements then, normal values are taken by their values, associative arrays are taken by their associated values and multidimentional arrays are displayed as “Array” at the end of the sorted list.


Ex. Extracting elements from array
<html><head><title>extracting elements from array</title></head>
$arr = array("red", "green", "blue", "yellow", "pink");

echo("<h2>Before modifying the array</h2><br>");
foreach($arr as $colorname){

#extract element from begininig of the array
$temp = array_shift($arr);
echo ("<h4>extracted element from begining is:   $temp</h4><br>");

#extract element from the ending of the array
$temp = array_pop($arr);
echo ("<h4>extracted element from last is:   $temp</h4><br>");

echo("<h2>After removing the elements from the array</h2><br>");
foreach($arr as $colorname){

echo("<h2>After sorting the elements of the  array</h2><br>");
foreach($arr as $colorname){



  • Syntax: array_merge(array1, array2, array3 ….arrayn)
  • This function takes minimum two arguments of type array and returns the combined elements of the arrays.
  • The resultant array should be stored in another variable.
  • You can merge more than two arrays together.
  • Always the first array elements are figured first and then the elements of arrays as they appear in sequence.


Ex. Merging arrays
<html><head><title>merging arrays</title></head>
$arr1 = array("red","green", "blue");
$arr2 =         array(56.3453, 34, 566, "pink");
$arr3 = array(345, "test", 43, "mesh");

#merging all the three arrays together and forming a new array
$arr = array_merge($arr1, $arr2, $arr3);

echo("<h2>After merging the three arrays</h2><br>");
foreach($arr as $colorname){



  • Syntax: array_slice(array, startindex, numberofelements)
  • This function takes minimum two elements.
  • First argument is the array from which we want to slice and remove the elements.
  • Second argument is the starting index of the element which you want to slice from the given array.
  • Third argument is the number of the elements which you need to slice from the given array.
  • First two arguments are compulsory, ie array name and starting index.
  • Third argument is optional.  If you mention the number of elements to be extracted they will be extracted otherwise the elements till the end of the array are extracted completely.
  • Slicing an array does not effect the original array in any way.
  • The sliced elements from the array should be stored in a different variable.


Ex. Slicing arrays
<html><head><title>slicing arrays</title></head>
$arr = array("red","green", "blue", 56.3453, 34, 566, "pink");
echo("<h2>Before slicing the array</h2>");
foreach($arr as $name){

#slicing the array and forming a new array
$temp =array_slice($arr, 2, 3);
echo("<h2>The sliced and extracted elements are </h2>");
foreach($temp as $name){

echo("<h2>After slicing elements the original array is </h2>");
foreach($arr as $name){

Browser details

  • The environment of the user is enclosed in the variable “HTTP_USER_AGENT”.
  • We have to seek this variable by using the “getenv()” function.
  • Preg_match() function in php allows to match the given string with the environment variable and results in true or false if found.
  • Syntax of preg_match(): preg_match(“/string to seek/”, “string to search”);
  • “string to seek” is the string which we have to find within the environment variable which is stored using getenv()function.
  • “String to search” is a variable in which the environment of the user is saved using getenv() function.


Ex. Browser details
<html><head><title>Browser content</title></head>

<?php $viewer = getenv("HTTP_USER_AGENT");

          $browser ="an unidentified browser";

          if(preg_match("/MSIE/i", "$viewer"))
{$browser ="Internet explorer";}

else if(preg_match("/Netscape/i","$viewer"))

          else if(preg_match("/Opera/i", "$viewer"))
{$browser = "Opera";}

$platform ="an unidentified platform";

          if(preg_match("/Windows/i", "$viewer"))

                   {$platform = "Windows"; }

else if(preg_match("/Linux/i","$viewer"))

                   {$platform = "Linux";}

          echo ("you are using $browser on $platform");

Date and time

  • The PHP date() function returns the current date and time on the server.
  • It takes only one argument as the string.
  • The string is formatted with the characters listed in the table below.
  • The hours returned is the standard GMT if you need the correct time you have to adjust according to the time zone.




prints “am” or “pm”


prints “AM” or “PM”


Hour in 12- hour format (1-12)


Hour in 12- hour format (01-12)


Hour in 24-hour format (0-23)


Hour in 24-hour format (01-23)


Minutes (00-59)


Seconds (00-59)


Time zone offset in seconds (-43200 to 43200)


Seconds since January 1, 1970 00:00:00 GMT


Day of the Month (1-31)


Day of the Month (01-31)


Day of the week (Mon – Sun)


Day of the week (Monday – Sunday)


Day of the week (0-6) from Sunday to Saturday


Month (Jan – Dec)


Month (January – December)


Month (1-12)


Month (01-12)


Year (09)


Year (2009)


day of the year (0-365)


Number of days in a given month (28 – 31)


English ordinal suffix (1st, 2nd etc)

Ex.      $today = date (“j M, Y”);    prints 3 Sep, 2009
$today = date (“d.m.y”);     prints 11.20.05
$today = date (“g:I a”);      prints 11.20 am
$today = date          (“H:i:s”);       prints 11.20.50


Ex. Date function
<html><head><title>Date function</title></head>

$hour = date("G");
$now = date ("g:i:s a");

$msg = "Good Evening.";
if($hour <12) $msg = "Good Morning.";
if($hour <18) $msg = "Good Afternoon.";

          echo ("$msg! the time is $now");

Random Numbers

  • Random numbers are numbers generated between the given value every time you call for display.
  • rand() function takes two arguments. 
  • First is the starting number and second is the last number.  Both should be integers.
  • Before using rand() function you have seed the microtime by using “srand()” function.
  • srand() function takes microtime() function multiplied to one million.
  • This is useful in showing images continuosly one after the other.
  • The example demonstrates the random numbers.  See that everytime you refresh the browser the numbers are different.


Ex. Random numbers
<html><head><title>random numbers</title></head>

srand(microtime() * 1000000);
$num = rand (1,100);
echo ("microtime : ".microtime()."<br>");
echo ("Random number : ".$num."<br>");
$num = rand (1,100);
echo ("another random number : ".$num);

Reading the form values

  • When the submit button is pressed in the web page, all the form data of HTML is sent to the server in variable and value pairs.
  • The forms “action” attribute specifies the php file which is going to handle the form.
  • The html “name” attributes are sent as variable names to php.
  • The variable names are same as name in html except for we use them putting a dollar symbol before all the names.


Ex.using form values(form values.html)
<html><head><title>html form</title>
<form name="f" action="form values.php" method = "post">
<b>Please enter your first name</b><br>
<input type="test" size="45" name="username"><br>

<p><b> Please select your favourite color wine : </b><br>
<input type="radio" name = "color" value="white"> white
<input type="radio" name = "color" value="rose"> Rose
<input type ="radio" name = "color" value="red"> Red <br>

<p><b> Please enter your favourite dish :</b><br>
<input type="text" size="45" name = "dish"><br><br>
<input type="submit" value = "submit this form">
<p> <input type="reset" value="clear">


Ex.using form values(form values.php)
<html><head><title>form response</title>

if($_POST[username] != null)         echo ("Thanks for your selecting $_POST[username]<hr>");

if(($_POST[color] != null) && ($_POST[dish] != null)){
$msg = "you really enjoy $_POST[dish] <br>";
$msg.= " - especially with a nice $_POST[color] wine";
echo ($msg);

String manipulation

  • strlen(), strrev(), strtoupper(), strtolower(), ucwords() are few functions which are used for manipulation of strings in php.
  • They take one string as their argument.
  • strlen() returns the length of the given string.
  • strrev() returns the reversed string of the argument.
  • strtoupper() returns the value of argument in upper case characters.
  • strtolower() returns the value of the argument in lower case characters.
  • ucwords() returns the string with each word of the given string capitalized.


Ex.string manipulation(HTML file)
<html><head><title>string manipulation</title>
<form action = "string manipulation.php" method="post">
<b> Enter some text here: </b><br/>
<textarea name ="txt" rows = "3" cols ="45"></textarea><br>
<p><input type="radio" name="fcn" value="strlen">Find the text length
<p><input type="radio" name="fcn" value="strrev">Reverse the text
<p><input type="radio" name="fcn" value="strtoupper">Change text to Uppercase
<p><input type="radio" name="fcn" value="strtolower">Change text to Lowercase
<p><input type="radio" name="fcn" value="ucwords">Change every first character of word to uppercase
<input type="submit" value="change">


Ex. String manipulation (php file)
<html><head><title>string manipulation</title>

Reloading a page

  • In php, the file will simply be reloaded if it has a form and its action is given as value “PHP_SELF”.
  • This “PHP_SELF” variable has a special meaning to the PHP pharser.  It simply tells the server to reload the given page.
  • LOGIC: The code for html (on the client side) and the code for response (on the server side) both are written in the same file with PHP extension.  The complete file will consist of two codes one for dynamically creating a html file for the user and the other for response as php code.  A variable or a if condition is set to null in the first loading of the file and when the user responds by changing the values of the variables.  The block for the response for the user is initiated.  The same is demonstrated in the following example.
  • header() this function has a special meaning for the php pharser.  These are generally server directives.
  • syntax: header(string header, [bool replace],[int http_response_code])
  • For example: -
  • header(“Location: url”) will take the browser to the new location as specified by the url in the above string, when the php pharser reads this command.
  • header(“Cache-Control: no-cache”) will load the page afresh everytime it is refreshed or reloaded by the internal commands of the php file.  It avoids the conventional reload of the page from the history.


Ex.reloading page
<html><head><title>switch Statement</title></head><body>
header("Cache-Control : no-cache");
global $num;
$num= $_POST['fnum'];
global $guess;
$guess= $_POST['fguess'];

          function setnum(){
global $num;
srand((double)microtime() * 1000000);
$num= rand(1,20);

<html><head><title>Number guess </title></head><body>

$msg="I have thought of a number between 1 and 20";
$msg.="<h3>guess what it is ...</h3>";

#error message for invalid entries
if($num != null and !is_numeric($guess)){
$msg="Your guess was invalid <h3> Try Again!</h3>";

else if($guess == $num){
if($num != null){
$msg="CORRECT! - THE NUMBER WAS ".$num;
$msg.="<h3><a href=\"$PHP_SELF\">";
$msg.="CLICK HERE TO TRY AGAIN??</a></h3>";

else if($guess > $num){
$msg="You guessed $guess <h3>My number is lower!</h3>";

else if($guess < $num){
$msg="You guessed $guess <h3>My number is higher!</h3>";


<form action="<?php $PHP_SELF ?>" method ="post">
<input type="hidden" name ="fnum" value="<?php echo($num);?>" >
Guess: <input type="text" name="fguess">
<input type="submit" value="submit">

Browser Redirection

  • Browser when reloaded using the “PHP_SELF” variable you can use headers to relocate it to another page on the web or local drive.
  • When the location object remains “null” when the web page is loaded for the first time, there is no change in the page but when the user selects a choice of page and clicks submit, the browser initializes the location object in the header() function to the given choice and the page gets redirected to the given option. 
  • This code is demonstrated in the example below.
  • Examine that the exit() function is used in the header.  This will come into action when the location object is initialized. 
  • This function will stop the browser from executed further code after this code.


Ex. Redirecting web page
if($_POST['location'] != null){
$loc = $_POST['location'];
choose a site to visit:
<form action="<?php $PHP_SELF ?>" method="post">
<select name="location">
<option value="http://www.google.com.np/">Google</option>
<option value="http://www.yahoo.com/">Yahoo</option>
<option value="\\cserver\staffdata$\chandra\tests\marquedemo.html">Marque Demo on Z drive</option>
<input type="submit" name="submit" value ="Go">

Working with files
Displaying directory

  • Directories in the server can be displayed in the browser.
  • First the name of an existing directory is assigned to a variable.
  • The opendir() takes one string as its argument, that is the name of the existing directory, and returns an handle to the directory.
  • This handle should reference should be stored in a variable for further use.
  • The readdir() and closedir() functions take one argument, that is the handle of a directory.
  • closedir() function closed the connection to the directory handle.
  • readdir() reads the files on the directory one by one. 
  • Each time the file is read, a true is returned, else if no file is read, then it returns a false.
  • Each time the file is read from the directory, the pointer stops at the next file.
  • So this reading is accomplished by keeping the code inside a while loop and stopped when the readdir() returns a false when it encounters the end of the directory.


Ex. Display directory
#for windows...
$dirname = "c:\program files";
$dir = opendir($dirname);
while(($file = readdir($dir)) != false) {
if(($file !=".") and ($file !=".."))
$file_list.= "<li> $file";
<html><head><title>Display directory</title></head>
<p>Files in <?php echo ($dirname); ?> </p>
<ol type="1" >
<?php echo ($file_list); ?>

Copying and renaming files

  • Files in the server can be copied and renamed using php code.
  • copy() function requires two strings viz., first string giving the name of the source file in string format and the second argument giving the name of the destination file in string format.
  • The following programe tries to copy the file and if it fails it displays a message regarding the error.
  • If the copy() function is successful in copying the file it returns true, else false.
  • Since the files follow the DOS convensions in windows, the file names are not case sensitive.
  • Files are overwritten.


Ex. Copying files
$source = "welcome.php";
$dest = "C:\wamp\www\PHP\WELCOME.php";

if(copy($source, $dest)) $msg="copied $source<br> to $dest";

else $msg="Unable to copy $source";

<html><head><title>copying files</title></head>
<?php echo($msg);?>

Renaming files

  • rename() function allows us to copy files.
  • rename() function takes two arguments, one for the original file which has to be changed and the second argument for the file into which the original file has to be renamed to.
  • Both the name s of the files should  be in the format of a string.
  • rename() function returns a true if it succeeds or returns a false in case of failure.


Ex.renaming file
$source = "welcome.php";
$dest = "welcome to aptech.php";

if(rename($source, $dest)) $msg="renamed $source to $dest";

else $msg="Unable to rename $source";

<html><head><title>copying files</title></head>
<?php echo($msg);?>

Deleting File

  • unlink() function is used to delete a file from the server directory.  To delete rename and copy files you need to have the permission.
  • This function takes one argument in the format of a string, which is the name of the existing file name.
  • unlink() function returns “true” if the given file has been deleted else returns a false.


Ex.deleting file
function try_delete($file){
echo("$file<br/> has been deleted<hr>");
echo("Unable to delete $file<hr/>");

<html><head><title>Deleting files</title></head><body>                                    
$fileA = "welcome to aptech.php";
$fileB = "non existing";


Opening & closing files

  • By default files in php can be opened on the server’s default directory(web root).
  • there are different modes of opening files.
  • fopen() is a php function to open the files.  it takes two arguments.
  • first argument specifies the file name and second argument specifies the mode.
  • if the fopen() is successful in opening a file it returns a “file pointer” else it will return “false”.
  • File modes for php are  “r” for read , “w” for write, “a” for append and “+” symbol means both read and write.
  • Meaning  of the modes for opening the files is given as below.


Opens the file for reading only.
Places the file pointer at the beginning of the file.


Opens the file for reading and writing.
places the file pointer at the beginning of the file.


opens the file for writing only
places the file pointer  at the beginning o the file and truncates the file to zero length.
if the file does not exist this will attempt to create it.


opens the file for reading and writing.
places the file pointer  at the beginning o the file and truncates the file to zero length.
if the file does not exist this will attempt to create it.


opens the file for writing only.
places the file pointer at the end of the file.
if the file dos not exist this will attempt to create it.


opens the file for reading and writing.
places the file pointer at the end of the file.
If the file does not exist this will attempt to create it.


Write only. Creates a new file. Returns FALSE and an error if file already exists


Read/Write. Creates a new file. Returns FALSE and an error if file already exists


  • after using the file it is important to close the file using fclose() function which takes the file pointer as its only argument.
  • fclose() returns “true” if it has succeeded to close the file or returns “false”.

Check End-of-file

  • The feof() function checks if the "end-of-file" (EOF) has been reached.
  • The feof() function is useful for looping through data of unknown length.
  • Note: You cannot read from files opened in w, a, and x mode!
  • ex. f (feof($file)) echo "End of file";

Reading a File Line by Line

  • The fgets() function is used to read a single line from a file.
  • Note: After a call to this function the file pointer has moved to the next line.


Ex. reading file
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
  echo fgets($file). "<br />";

Reading a File Character by Character

  • he fgetc() function is used to read a single character from a file.
  • Note: After a call to this function the file pointer moves to the next character.


Ex. reading file
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  echo fgetc($file);

Server Side Includes (SSI)

  • You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.
  • The two functions are identical in every way, except how they handle errors:
  • include() generates a warning, but the script will continue execution
  • require() generates a fatal error, and the script will stop
  • These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.


Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).

PHP include() Function

  • The include() function takes all the content in a specified file and includes it in the current file.
  • If an error occurs, the include() function generates a warning, but the script will continue execution.


Ex: include demo

First make a file called menu.php with the code given below.

<a href="/home.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a> 
<a href="/about.php">About Us</a> 
<a href="/contact.php">Contact Us</a>


Now include the line <?php include("menu.php"); ?>”  in all the files listed in the menu file given above.  This line should be included in all the six files containing the above line as given below.  This will produce the links at the top of every file as a menu without the need to repeat the code.

<div class="leftmenu">
<?php include("menu.php"); ?>

<h1>Welcome to my home page.</h1>
<p>The main content of the file will go here</p>


PHP require() Function

The require() function is identical to include(), except that it handles errors differently.
If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.  The error message will look like the one given below.


Error message:
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
in C:\home\website\test.php on line 5


  • Cookies are small files stored in the user computer.
  • We can store upto 4000 characters in one cookie.
  • 20 cookies are allowed for one site.
  • Max of 300 cookies can held by one client system.
  • Setcookie() is the function used to create the cookies in PHP.  
  • This function takes six arguments but only one first argument (that is the name of the cookie is enough to create the cookie).


Arguments for setcookie():
Name : this sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS.  This named variable will be accessible to subsequent PHP page scripts.
Value: this sets the value of the named variable and is the content that you a ctualy want to store.
Expiry: This specifies a future time, in seconds since 00;00;00 GMT on 1st Jan 1970, at which the cookie will become inaccessible.  If this argument is not explicitly set the cookie will automatically expire when the web browser is closed.
Path : This specifies the directories for which the cookie is valid.  A single forward slash character permits the cookie to be valid for all directories on the server.  If a directory is explicitly specified then the cookie is only valid for pages within that directory.
Domain: This can be used to specify the domain name in very large domains and must contain at least two periods to be valid.  It this argument is not explicitly specified the default value is the host name of the server that created the cookie.  All coopkies are only valid for the host and domain which crated them.

Security: This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS, otherwise if set to 0 the cookie can be sent by regular HTTP.

Ex.          Setcookie(“id”, “x12345”, time() + 86400, “/”, “”,0);
Setcookie(“id”, “x12345”, time() + 87666);


EX. Set cookie
if(($_POST[user] != null) and ($_POST[color] !=null)){
setcookie("firstname", $user, time()+259200);
setcookie("fontcolor", $color , time()+259200);
header("location:get cookie.php");

<html><head><title>set cookie data</title></head><body>
<form action ="<?php echo($PHP_SELF); ?>" method = "post">

Please enter your first name:
<input type="text" name = "user"> <br><br>

please choose your favourite fot color : <br>
<input type ="radio" name = "color" value = "#FF0000">Red
<input type ="radio" name = "color" value = "#00FF00">Green
<input type ="radio" name = "color" value = "#0000FF">Blue
<input type= "submit" value = "submit">

Reading cookie data

  • To read the cookie from the cookies which are set by the form earlier you need to access them using the system variable $_COOKIES[ ] variable.
  • The name of the cookie which you have set should be given in between the parenthesis of $_COOKIES[ name ].


Ex.get cookie
<html><head><title>get cookie data</title>
<style type="text/css">
body {color:<?php echo($_COOKIES[fontcolor]); ?>}
<h1 align="center"> Hello <?php echo($_COOKIES[firstname]);?> ! </h1>
<h1 align="center"> Welcome to Cookies world </h1>

Connecting to MYSQL

  • PHP has mysql_connect() function for connecting to the database.
  • It has three arguments viz domain name, user name, & password.
  • If the connection succeeds true is returned and if it fails false  is returned.

NOTE:grant all privileges on *.* to <username>@localhost identified by <”password”> with grant option;” is used to create a new user with grant permission.


Ex. Getting connected
$user = "john";
$con = mysql_connect("localhost", $user, "aptech");
if($con){$msg = "congratulations $user, you got connected to MYSQL"; }

<html><head><title>getting connected</title></head><body>
<h3> <?php echo ($msg); ?> </h3>  

Showing Databases

  • “show databases” in SQL is equal to “mysql_list_dbs()” in php.
  • But the result received from the database cannot be accessed directly in php.
  • First the result is received by the php and placed in the result set which is in the form of a table.
  • To know the number of rows received in result set, we have mysql_num_rows() function which takes “result set” as its argument.
  • After knowing the number of rows received in the result set we can read the values one after the other row using mysql_tablename() function.  Names of both databases and tables can be read from the result set using this function.
  • mysql_tablename() receives two arguments (a) result set and (b) row number.
  • Prefix “@” symbol before this function to suppress the warning messages.


Ex. Showing databases
$user = "john";
$con = @mysql_connect("localhost", $user, "aptech") or
die("sorry - could not connect to MYSQL");
$rs = mysql_list_dbs($con);

for($row=0; $row < mysql_num_rows($rs); $row++)
$db_list.=mysql_tablename($rs, $row)."<br>";

<html><head><title>showing databases</title></head><body>
<h3> <?php echo ($db_list); ?> </h3>   

Showing tables

  • While in sql you have to use atleast one database before you select and list the names of the tables.  Without the use command you cannot list the tables.
  • In php we don’t need to give the command  “use database” Once you have listed the databases, then automatically you can list the tables of any database by using the “mysql_list_dbs()”.
  • Mysql_list_dbs() function takes the name of the database you want to use, from which you would like to list the names of the tables.


Ex. Showing tables


$con = @mysql_connect("localhost","john","aptech") or
die("sorry no connection please");


$rs1 = mysql_list_tables(cc);
for($row=0; $row < mysql_num_rows($rs1); $row++)



Ex. Listing databases and tables
$con = @mysql_connect("localhost","john","aptech") or
die("sorry no connection please");
for ($row =0; $row < mysql_num_rows($rs1); $row++){
$this_db = mysql_tablename($rs1,$row);

if($this_db != "mysql"){
$rs2 = mysql_list_tables($this_db);
for($num=0; $num < mysql_num_rows($rs2); $num++){
$list.="-".mysql_tablename($rs2, $num)."<br>";
<BODY><?php echo($list); ?> </body></html>

Creating a database

  • In SQL we use ‘create database’ for creating a database while in PHP we use mysql_create_db().
  • This function takes the name of the database to be created as its argument as a string.



  • The whole process is complete in three steps. 
  • First we have to ask for the number of columns/fields which the user needs to create.
  • Then we have to create the number of lines with field name, type, size etc.  We have also to provide two text boxes for the user to enter the name of the database and table to be created.
  • The table should be created with the given table name and database using the mysql_query() function.



  • The form uses the reloading technique using the $PHP_SELF variable.
  • Only one “if-else if- else” construct is used to load the page three times.
  • First “if” construct will allow the user to enter the number of fields/columns to create.
  • Second “else if” construct will allow the user to enter the details of the columns/fields of the table including type and size etc.
  • We use only HTML till this place.
  • All the HTML code is generated using PHP.
  • The complete HTML code is formed in a string and echoed to the user.
  • Third “else” clause will actually select the database which it has received from the user and then try to create the table.  If successful it will display the query string and also the message that the database is successful.


Ex.creating database
<htmL><HEAD><TITLE>creating databases</TITLE></HEAD>


if(!$_POST[fields] and !$_POST[db]){
$form = "<html><head><title>Column selections</title></head><body>";
$form.= "<form action=\"$PHP_SELF\" method=\"post\">";
$form.= "<h3>How many fields do you need to include in the new table?<hr>";
$form.="<br><input type=\"text\" name=\"fields\">";
$form.="<input type=\"submit\" value\"submit\">";


else if(!$_POST[db]){
$form="<form action =\"$PHP_SELF\" method=\"post\">";
$form.="Database: <input type=\"text\" name=\"db\"><br>";
$form.="Table Name: <input type=\"text\" name=\"table\"><br><hr>";
$form.="<h3>Select the Fields</h3><br>";

for($i=0; $i<$_POST[fields]; $i++){
$form.="Column Name:<input type=\"text\" name=\"name[$i]\">";
$form.="&nbsp &nbsp Type: <select name=\"type[$i]\">";
$form.="<option value=\"varchar\">varchar</option>";
$form.="<option value=\"int\">int</option>";
$form.="<option value=\"char\">char</option></select>";


#....include more options here if you need.

$form.="&nbsp &nbsp size:<input type=\"text\" name=\"size[$i]\" size=\"5\"><br>";

$form.="<br><input type=\"submit\" value=\"submit\">";


#make the connection to mysql
$con = @mysql_connect("localhost","john","aptech")
or die("Sorry : no connection");

#select the specified database
$rs = @mysql_select_db($_POST[db], $con)
or die ("Error in Database name");

#create the query
$sql = "create table $_POST[table](";

$namearr = $_POST[name];
$typearr = $_POST[type];
$sizearr = $_POST[size];

for($i=0; $i < count($namearr); $i++){

     #field name & data type
$sql.="$namearr[$i] $typearr[$i]";

#allow size specification for char and varchar types
if(($typearr[$i] =="char") or ($typearr[$i] == "varchar")){

     #if a size has been specified add it to the query
if($sizearr[$i] != ""){

#if this is not the final field add a comma
if(($i+1) != count($namearr)){


# display the SQL query
echo ("SQL COMMAND:$sql <hr>");


#execute the query - attempt to create the table
$result = mysql_query($sql, $con) or die ("err:query");

#confirm if successful
if($result) echo ("Result : table \"$_POST[table]\" has been created. ");

Inserting table data
Adding records to the database takes the same procedure as the earlier example.  It takes the database name and table.  To select the table use mysql_select() function, then an SQL query containing the record data is supplied as the argument to the mysql_query() function.

the SQL query string would be “insert into <table name>” followed by the field names and list of values.

All the values which are of type string should be enclosed within a pair of quotes.

Ex. Using the above database creating example first create a table as given below:-

     Name of table : St (student)












Ex.Inserting records
<html><head><title>Inserting records</title></head>
<form action="<?php echo($PHP_SELF); ?>" method="post">
Student ID :<input type="text" name="sid" size="5"><br>
Student Name:<input type="text" name="sname" size="25"><br>
Maths: <input type="text" name="m1" size="5"><br>
Science: <input type="text" name="m2" size="5"><br>
<input type="submit" value="submit">


#ensure all fields have entries

if($_POST[sid] and $_POST[sname] and $_POST[m1] and 


$con = @mysql_connect("localhost","john","aptech") or
die("sorry no connection please");

#select the specified database
$rs=mysql_select_db("student",$con) or die("sorry database not


#Create the query
$sql="insert into st (sid, sname, m1, m2) values

($_POST[sid],\"$_POST[sname]\", $_POST[m1], $_POST[m2])";

#execute the query
$rs = mysql_query($sql, $con);

#confirm the added record details
if($rs){echo("Record added:$sid, $sname, $m1, $m2");}

Altering the table structure

  • The altering process does not need any additional functions.
  • Get connected using the mysql_connect().
  • Select the specified database using mysql_select_db().
  • Execute the query using mysql_query().
  • Use the sql query syntax as you use at command prompt of MYSQL.


Ex.Altering table
<html><head><title>Inserting records</title></head>

#Get connected first

$con = @mysql_connect("localhost","john","aptech") or
die("sorry no connection please");

#select the specified database
$rs=mysql_select_db("student",$con) or die("sorry database not


#Create the query to modify sid as not null
$sql="alter table st modify sid int not null";


#execute the query
$rs = mysql_query($sql, $con) or die("error in query:$sql");


#confirm the modified details.
if($rs) {
echo("Field \"sid\" has been modified to not null");


Retrieving data records from tables

  • Get connected using the mysql_connect().
  • Select the specified database using mysql_select_db().
  • Execute the query using mysql_query().
  • While reading the data from the result set we can use mysql_fetch_array().
  • This array takes one parameter “result set” and returns a single row/record of information from the table.
  • Each field is read from the table using the variable name as an array with field names as its index as demonstrated below.
  • The result from mysql_fetch_array is assigned to $row variable.
  • Then the field is extracted one by one using $row[field name].
  • For better presentation a table has been used.


Ex.Retriving data
<html><head><title>Inserting records</title></head>

#Get connected first

$con = @mysql_connect("localhost","john","aptech") or
die("sorry no connection please");

#select the specified database
$rs=mysql_select_db("student",$con) or die("sorry database not


#Create the query to select from table st
$sql="select * from st";

#execute the query
$rs = mysql_query($sql, $con) or die("error in query:$sql");

#write the data
echo("<table border=\"2\" width=\"50%\">");
echo("<tr><td><b>SID </b></td><td>".$row['sid']."</td>");
echo("<td><b>SName </b></td><td>".$row['sname']."</td>");
echo("<td><b>M1 </b></td><td>".$row['m1']."</td>");
echo("<td><b>M2 </b></td><td>".$row['m2']."</td>");


M Y   S Q L

  • SQL (Structured Query Language) is a standard programming language for generating, manipulating, and retrieving information from a relational database.
  • SQL is a standardized language for most of the existing databases.  It is a common language for databases.
  • Table: 
  • A table is a container that stores data in columns and rows.
  • You can imagine an excel sheet as it stores information in rows and columns with the only difference that a table can hold as much information as you need.
  • Each column has a name, this name is also called as “field”.
  • Each row has a set of fields/names of columns and this row is called as a “record”.
  • Database:
  •  A database is a collection of related tables.
  • The system stores the data encrypted but the data can be retrieved and written by the user normally. 
  • Data is stored along with meta-data (or information about the data) written by the system.
  • Database can be imagined like a folder which contains collections of files.
  • Type of databases
  • Hierarchical database:In computerized database systems, data was stored and represented to users in various ways. In a hierarchical database system, for example, data is represented as one or more tree structures.  As we use the directory levels to represent different levels of information these databases were saved in flat files (normal files) in computers.
  • Network database: exposes sets of records and sets of links that define relationships between different records.  The records should be traced using links and reproduced for use.
  • Relational Database:  In 1970 Dr. E. F. Codd of IBM's research laboratory published a paper entitled "A Relational Model of Data for Large Shared Data Banks" that suggested data be represented as sets of tables. Rather than using pointers to navigate between related entities, redundant data is used to link records in different tables.  In simple words relational data base is a collection of inter-related tables  joined in a variety of ways.








Men in Black


Star Wars










  • First table lists several video titles sorted numerically by video_id.
  • Second table describes a relationship between the table that links each member to the video they have rented.
  • Note the usage of underscore “_” in the column/field names because spaces are not allowed in field names.


Entity: A single existence, an independent item like customer, parts, geographic location etc.

Column: A single column in database refers to a field.

Row: A set of columns or fields which form a complete record or a piece of data in the table.

Table:  Collection of rows and columns (or fields and records) a set of related data stored in the memory.

Result Set:  Generally a result of a query made on a particular data table.

Primary Key:  one column or field which is made as unique (without any duplicate values) in the table.  So that when we search we can catch hold of the specific record with the help of primary key. For example id of person, student number etc.

Foreign Key:  a single column or field which is unique to two different tables.  This key generally picks up related information about one singe entity.  For example in the table given above for relational databases the “Video_id” is unique to both the tables.

  • Working with MYSQL

When you open the command prompt.  You are ready to use the SQL commands. 
Every SQL command is followed by a semicolon (;).

  • NOTE: 
  • Use the shortcut icon for entering the SQL console.
  • Click  “Enter” when the system asks for password.
  • To quit SQL prompt enter “\q”.
  • To clear contents enter “\c”.
  • For help enter “\h”.
  • By default MYSQL creates two databases one for the information/test and one MYSQL database which stores the system information.



select now();

Get the current data and time.

show databases;

Shows the existing data bases

use database;

use the given database. Ex. Use student;

show tables;

shows the existing tables in the given database.

explain table;

gives the complete format of the table like name of the field etc.
Ex. Explain student.

Show character set;

Shows the character set for character of different languages.


Data types in SQL




-128 to 127 and 0 to 255 for unsigned.


-32,768 to 32,767 and 0 to 65,535 for unsigned.


-8,388,608 to 8,388,607 and 0 to 16,777,215 for unsigned.


-2,147,483,648 to 2,147,483,647 and 0 to 4,294,967,295 for unsigned.


-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 and 0 to 18,446,744,073,709,551,615 for unsigned.


  • A floating point number that can specify the number of permissible digits.  For example decimal (3, 2) allows -999.99 to 999.99.




-3.402823466E+38 to -1.175494351E-38 and 1.175494351E-38 to 3.402823466E+38


1.7976931348623157E+308 to -2.2250738585072014E-308 and 2.2250738585072014E-308 to 1.7976931348623157E+308


  • A date in the YYYY-MM-DD format.
  • Range : 1000-01-01 to 9999-12-31


  • A time in the HH:MM:SS format
  • Range: -838:59:59 to 838:59:59.


  • A combined date and time I the format YYYY-MM-DD HH:MM:SS
  • Range: 1000-01-01 00:00:00 to 9999-12-31 23:59:59.


  • A year in either YY or YYYY format.
  • Range: 1901 – 2155.


  • Automatic date and time of last record entry.
  • Range: 1970-01-01 00:00:00 to 2037-12-31 23:59:59.


  • A string of defined fixed length upto 255 characters long. 
  • For example, char (100) pads a smaller string to make it 100 characters long.
  • Can avoid mentioning size. 
  • By default 1 char.
  • Default value is null.



  • A string of defined variable length upto 255 characters long that is stored without padding.
  • Size should be mentioned.





  • If the data being loaded into a text column exceeds the maximum size for that type, the data will be truncated.
  • Unlike a varchar column, trailing spaces will not be removed when data is loaded into the column.
  • When using text columns for sorting or grouping, only the first 1,024 bytes are used






  • A binary type for variable data


  • A single string value from a defined list.  For example, enum(“red”, “green”, “blue”) allows entry of any of these three colors only.


  • A string or multiple strings from a defined list.  For example, set(“red”, “green”, “blue”) allows entry of one or more of these three colours.

Creating Datase:
Database can be created using “create database” followed by the name of the database. A database can be thought of like a directory which would contain many files called tables.


NOTE: Every line in MY SQL should end with a semicolon.

Ex. Create database students;
Create database personal;
Create database Employee;

Using Database:
“use” keyword is used to use a database.
Ex.          Use students;
Use personal;
Use employee;

Creating tables:

  • Table structure is first created using “create table” keyword and all the data variable names along with the type of data they carry and conditions, if needed will be given.
  • After “create table” keyword the name of the table is given followed by a pair of parenthesis, in which a list of fields followed by its type is mentioned.
  • Fields are put inside the parenthesis.
  • Each field is separated by a comma.
  • Name of variable is followed by its data type.

Ex. Create table student (sname varchar(25), sno int); 

Modifiers (Checks & constraints)
Checks and constraints are conditions which are applied on the entry of data.  It restricts the data in some form.  The following table depicts the types of modifiers: -



not null

Tells that each record must include data.  It cannot be left empty.


Tells that every record has a unique value.  No repetition of values.


Only for numeric columns. Will tell the system to generate automatically, a number more than the previous one.

primary key()

tells the system that the given column should be used as primary key.  Generally given at the end of the list of columns.

Ex. Create table cars(id int auto_increment, make varchar(20) not null, model varchar(20) not null unique, primary_key(id));

Create a table “pers”.


Person table.



Allowable values






M, F










Gender can be created using :

  • Gender char(1) check (gender in (‘m’, ‘f’)),
  • Gender enum(‘m’,’f’),














int auto_increment


int unique (primary_key)




int unique











medium int

Insert Statement

  • “Insert into” keyword is used to insert values into a table.
  • “insert into” is followed by the table name and then field list is included in a pair of parenthesis followed by “values” keyword and pair of parenthesis containing values.
  • All the values and columns inside the parenthesis should be separated by a comma.

If you insert without any field list you should mention all the values.  But if you mention the column list then only the columns which are given will be entered with the values.


Ex.  insert into item (itemcode, itemname, rate) values (0056,”colgate”, 24.50);
Insert into item values (0056,”colgate”, 23.50);
Insert into item (itemcode, itemname) values (0056,”colgate”);
Insert into item (itemcode, itemname, rate) values (445, “RIN”, 33.50), (6645, “surf”, 88.5);

Update Statement

  • Syntax:  update <table name> set <field>  = <value>  where <cond>;
  • Update statement is used when we need to correct the data which is already existing in the table.
  • Using “update” we can update/change the existing data of a single or multiple fields with the given values.
  • All the records matching the condition will be replaced with the given values.


Ex. update item set itemname = “lux” where code=0056;

Altering table structure of fields (Table definition)

  • The definition of the table (field type) can be changed even after the table has been created.
  • A field can also be added to the existing table.
  • Syntax: alter table <table name> modify <field name> type modifiers.
  • Syntax: alter table <table name> add <field name>.
  • Syntax: alter table <table name> drop <field name>.
  • The second syntax has been included in the MY SQL 4.  The “add” clause can add fields to the existing table structure.
  • “Modify” clause can modify the existing structure  of the field.  Be careful, because illegal conversions like changing the entire data type is not possible,  and changing the primary key is also not possible.
  • The third syntax using drop keyword has been introduced in MYSQL 4.  This clause can remove the given field from the table.


Ex.          alter  table item modify itemname varchar(70);
                alter  table item add itemsale int;
alter  table item drop itemsale;

Deleting Records

  • Delete statement deletes the record for the given condition.
  • If there are several records matching the condition then all them will be deleted.
  • SYNTAX: delete from <table name> where <condition>;


Ex: delete from item where code=056;

Deleting tables

  • You can use the drop statement for deleting the entire table. 
  • The entire table along with the data will be deleted.
  • Syntax:  drop table <table name>;

Ex.          drop table item;

Deleting Databases

  • You can use the drop statement for deleting the entire database along with the tables in it.
  • Syntax:  drop database <database name>;

Ex.          drop database person;

Select statement

  • Select statement is used to retrieve data from the table.
  • “ * ” (asterisk) refers to all the fields in the table.
  • You can even select individual fields separated by a comma.
  • You can also mention the condition and select the records.
  • You can sort the data which has been retrieved by the statement, for display.

Syntax:   select <field, field, …..> from <table name> where <condition> order by <field name>;

Ex.          select * from item;
select itemcode, itemname from item;
select itemcode, itemrate, itemsale from item where code = 056;
select itemname from item where code=056 order by code;


Sign up to received our free newsletter!
E-mail ID:


Views: 5020 Times
Draw a Realistic Samsung Galaxy S2 â Photoshop Tutorial READ MORE
Views: 2600 Times
Google imagines environment-aware mobile adverts READ MORE
Views: 2505 Times
Facebook makes $10m charity payment to settle lawsuit READ MORE
Views: 5198 Times
How to Secure a Wireless Network from Hackers? READ MORE
Views: 7396 Times
Formatting and Clean Install of Windows 7 READ MORE

Home|IT News|Computer Tips|Video Tutorials|Download Softwares|Subjects|Contact Us
Copyright © 2018. Jumbo Education (Information Technology). All rights reserved.
Free counter and web stats

Large Visitor Globe