You are on page 1of 38

PHP Tutorial

PHP Basic
PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP HOME Intro Install Syntax Variables String Operators If...Else Switch Arrays While Loops or Loops !nctions or"s #$%E& #$POS&

PHP Advanced
PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP 'ate Incl!(e ile ile )ploa( *oo+ies Sessions E,"ail Sec!re E,"ail Error Exception ilter

PHP Database
MyS-L Intro(!ction MyS-L *onnect MyS-L *reate MyS-L Insert MyS-L Select MyS-L Where MyS-L Or(er .y MyS-L )p(ate MyS-L 'elete PHP O'.*

PHP XML
/ML Expat Parser /ML 'OM /ML Si"ple/ML

PHP and AJAX


A0A/ A0A/ A0A/ A0A/ A0A/ A0A/ A0A/ Intro PHP 'atabase /ML Li1e Search 2SS 2ea(er Poll

PHP Reference
PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP PHP Array *alen(ar 'ate 'irectory Error ilesyste" ilter &P H&&P Libx"l Mail Math Misc MyS-L Si"ple/ML String /ML 3ip

PHP Quiz
PHP -!i4

PHP

Certificate

PHP &!torial

PHP is a powerf!l tool for "a+ing (yna"ic an( interacti1e Web pages. PHP is the wi(ely,!se(5 free5 an( efficient alternati1e to co"petitors s!ch as Microsoft6s ASP. In o!r PHP t!torial yo! will learn abo!t PHP5 an( how to exec!te scripts on yo!r ser1er. Start learning PHP no !

PHP Intro(!ction
PHP is a ser1er,si(e scripting lang!age.

What 7o! Sho!l( Alrea(y 8now


.efore yo! contin!e yo! sho!l( ha1e a basic !n(erstan(ing of the following9

H&ML:/H&ML 0a1aScript

If yo! want to st!(y these s!b;ects first5 fin( the t!torials on o!r Ho"e page.

What is PHP<

PHP stan(s for PHP9 Hypertext Preprocessor PHP is a ser1er,si(e scripting lang!age5 li+e ASP PHP scripts are exec!te( on the ser1er PHP s!pports "any (atabases =MyS-L5 Infor"ix5 Oracle5 Sybase5 Soli(5 PostgreS-L5 %eneric O'.*5 etc.> PHP is an open so!rce software PHP is free to (ownloa( an( !se

What is a PHP ile<



PHP files can contain text5 H&ML tags an( scripts PHP files are ret!rne( to the browser as plain H&ML PHP files ha1e a file extension of ?.php?5 ?.php@?5 or ?.pht"l?

What is MyS-L<

MyS-L is a (atabase ser1er MyS-L is i(eal for both s"all an( large applications MyS-L s!pports stan(ar( S-L MyS-L co"piles on a n!"ber of platfor"s MyS-L is free to (ownloa( an( !se

PHP A MyS-L

PHP co"bine( with MyS-L are cross,platfor" =yo! can (e1elop in Win(ows an( ser1e on a )nix platfor">

Why PHP<

PHP r!ns on (ifferent platfor"s =Win(ows5 Lin!x5 )nix5 etc.> PHP is co"patible with al"ost all ser1ers !se( to(ay =Apache5 IIS5 etc.> PHP is 2EE to (ownloa( fro" the official PHP reso!rce9 www.php.net PHP is easy to learn an( r!ns efficiently on the ser1er si(e

Where to Start<
&o get access to a web ser1er with PHP s!pport5 yo! can9

Install Apache =or IIS> on yo!r own ser1er5 install PHP5 an( MyS-L Or fin( a web hosting plan with PHP an( MyS-L s!pport

PHP Installation
What (o yo! Bee(<
If yo!r ser1er s!pports PHP yo! (on6t nee( to (o anything. 0!st create so"e .php files in yo!r web (irectory5 an( the ser1er will parse the" for yo!. .eca!se it is free5 "ost web hosts offer PHP s!pport. Howe1er5 if yo!r ser1er (oes not s!pport PHP5 yo! "!st install PHP. Here is a lin+ to a goo( t!torial fro" PHP.net on how to install PHPC9http9::www.php.net:"an!al:en:install.php

'ownloa( PHP
'ownloa( PHP for free here9 http9::www.php.net:(ownloa(s.php

'ownloa( MyS-L 'atabase


'ownloa( MyS-L for free here9 http9::www."ysDl.co":(ownloa(s:

'ownloa( Apache Ser1er


'ownloa( Apache for free here9 http9::http(.apache.org:(ownloa(.cgi

PHP Syntax
&he PHP script is exec!te( on the ser1er5 an( the plain H&ML res!lt is sent bac+ to the browser.

.asic PHP Syntax


A PHP script always starts with "#$%$ an( en(s with #&. A PHP script can be place( anywhere in the (oc!"ent. On ser1ers with shorthan(,s!pport5 yo! can start a PHP script with E< an( en( with <F. or "axi"!" co"patibility5 we reco""en( that yo! !se the stan(ar( for" =E<php> rather than the shorthan( for".

<?php ?>
A PHP file "!st ha1e a .php extension. A PHP file nor"ally contains H&ML tags5 an( so"e PHP scripting co(e. .elow5 we ha1e an exa"ple of a si"ple PHP script that sen(s the text ?Hello Worl(? bac+ to the browser9

<html> <body> <?php echo "Hello World"; ?> </body> </html>


Each co(e line in PHP "!st en( with a se"icolon. &he se"icolon is a separator an( is !se( to (isting!ish one set of instr!ctions fro" another. &here are two basic state"ents to o!tp!t text with PHP9 ec%o an( $rint. In the exa"ple abo1e we ha1e !se( the echo state"ent to o!tp!t the text ?Hello Worl(?.

*o""ents in PHP
In PHP5 we !se '' to "a+e a one,line co""ent or '( an( (' to "a+e a co""ent bloc+9

<html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>

PHP Variables
Variables are ?containers? for storing infor"ation.

'o 7o! 2e"e"ber Algebra ro" School<


'o yo! re"e"ber algebra fro" school< xGC5 yGH5 4GxAy 'o yo! re"e"ber that a letter =li+e x> co!l( be !se( to hol( a 1al!e =li+e C>5 an( that yo! co!l( !se the infor"ation abo1e to calc!late the 1al!e of 4 to be II< &hese letters are calle( variables5 an( 1ariables can be !se( to hol( 1al!es =xGC> or expressions =4GxAy>.

PHP Variables
As with algebra5 PHP 1ariables are !se( to hol( 1al!es or expressions. A 1ariable can ha1e a short na"e5 li+e x5 or a "ore (escripti1e na"e5 li+e carBa"e. 2!les for PHP 1ariable na"es9

Variables in PHP starts with a # sign5 followe( by the na"e of the 1ariable &he 1ariable na"e "!st begin with a letter or the !n(erscore character A 1ariable na"e can only contain alpha,n!"eric characters an( !n(erscores =A,45 J,K5 an( $ > A 1ariable na"e sho!l( not contain spaces Variable na"es are case sensiti1e =y an( 7 are two (ifferent 1ariables>

*reating ='eclaring> PHP Variables


PHP has no co""an( for (eclaring a 1ariable. A 1ariable is create( the "o"ent yo! first assign a 1al!e to it9

$myCar=" ol!o";
After the exec!tion of the state"ent abo1e5 the 1ariable )*+ar will hol( the 1al!e ,olvo. Ti$- If yo! want to create a 1ariable witho!t assigning it a 1al!e5 then yo! assign it the 1al!e of null. Let6s create a 1ariable containing a string5 an( a 1ariable containing a n!"ber9

<?php $t"t="Hello World#";

$"=$%; ?>
.ote- When yo! assign a text 1al!e to a 1ariable5 p!t D!otes aro!n( the 1al!e.

PHP is a Loosely &ype( Lang!age


In PHP5 a 1ariable (oes not nee( to be (eclare( before a((ing a 1al!e to it. In the exa"ple abo1e5 notice that we (i( not ha1e to tell PHP which (ata type the 1ariable is. PHP a!to"atically con1erts the 1ariable to the correct (ata type5 (epen(ing on its 1al!e. In a strongly type( progra""ing lang!age5 yo! ha1e to (eclare =(efine> the type an( na"e of the 1ariable before !sing it.

PHP Variable Scope


&he scope of a 1ariable is the portion of the script in which the 1ariable can be reference(. PHP has fo!r (ifferent 1ariable scopes9

local global static para"eter

Local Scope
A 1ariable (eclare( it%in a PHP f!nction is local an( can only be accesse( within that f!nction. =the 1ariable has local scope>9

<?php $a = &; // 'lobal scope ()nction myTest*+ , echo $a; // local scope myTest*+; ?>
&he script abo1e will not pro(!ce any o!tp!t beca!se the echo state"ent refers to the local scope 1ariable #a5 which has not been assigne( a 1al!e within this scope.

7o! can ha1e local 1ariables with the sa"e na"e in (ifferent f!nctions5 beca!se local 1ariables are only recogni4e( by the f!nction in which they are (eclare(. Local 1ariables are (elete( as soon as the f!nction is co"plete(.

%lobal Scope
%lobal scope refers to any 1ariable that is (efine( o!tsi(e of any f!nction. %lobal 1ariables can be accesse( fro" any part of the script that is not insi(e a f!nction. &o access a global 1ariable fro" within a f!nction5 !se the global +eywor(9

<?php $a = &; $b = $.; ()nction myTest*+ , 'lobal $a/ $b; $b = $a 0 $b; myTest*+; echo $b; ?>
&he script abo1e will o!tp!t IC. PHP also stores all global 1ariables in an array calle( #%LO.ALSL indexM. Its in(ex is the na"e of the 1ariable. &his array is also accessible fro" within f!nctions an( can be !se( to !p(ate global 1ariables (irectly. &he exa"ple abo1e can be rewritten as this9

<?php $a = &; $b = $.; ()nction myTest*+ , $123452678b89 = $123452678a89 0 $123452678b89; myTest*+; echo $b; ?>

Static Scope
When a f!nction is co"plete(5 all of its 1ariables are nor"ally (elete(. Howe1er5 so"eti"es yo! want a local 1ariable to not be (elete(.

&o (o this5 !se the static +eywor( when yo! first (eclare the 1ariable9

static $remember:e;
&hen5 each ti"e the f!nction is calle(5 that 1ariable will still ha1e the infor"ation it containe( fro" the last ti"e the f!nction was calle(. .ote- &he 1ariable is still local to the f!nction.

Para"eters
A para"eter is a local 1ariable whose 1al!e is passe( to the f!nction by the calling co(e. Para"eters are (eclare( in a para"eter list as part of the f!nction (eclaration9

()nction myTest*$para$/$para;/<<<+ , // ()nction code Para"eters are also calle( arg!"ents. We will (isc!ss the" in "ore (etail when we tal+ abo!t f!nctions.

PHP String Variables


A string 1ariable is !se( to store an( "anip!late text.

String Variables in PHP


String 1ariables are !se( for 1al!es that contain characters. In this chapter we are going to loo+ at the "ost co""on f!nctions an( operators !se( to "anip!late strings in PHP. After we create a string we can "anip!late it. A string can be !se( (irectly in a f!nction or it can be store( in a 1ariable. .elow5 the PHP script assigns the text ?Hello Worl(? to a string 1ariable calle( #txt9

<?php $t"t="Hello World"; echo $t"t; ?>


&he o!tp!t of the co(e abo1e will be9

Hello World
Bow5 lets try to !se so"e (ifferent f!nctions an( operators to "anip!late the string.

&he *oncatenation Operator


&here is only one string operator in PHP. &he concatenation operator =.> is !se( to p!t two string 1al!es together. &o concatenate two string 1ariables together5 !se the concatenation operator9

<?php $t"t$="Hello World#"; $t"t;="What a nice day#"; echo $t"t$ < " " < $t"t;; ?>
&he o!tp!t of the co(e abo1e will be9

Hello World# What a nice day#


If we loo+ at the co(e abo1e yo! see that we !se( the concatenation operator two ti"es. &his is beca!se we ha( to insert a thir( string =a space character>5 to separate the two strings.

&he strlen=> f!nction


&he strlen=> f!nction is !se( to ret!rn the length of a string. Let6s fin( the length of a string9

<?php echo strlen*"Hello =orld#"+; ?>


&he o!tp!t of the co(e abo1e will be9

$;
&he length of a string is often !se( in loops or other f!nctions5 when it is i"portant to +now when the string en(s. =i.e. in a loop5 we wo!l( want to stop the loop after the last character in the string>.

&he strpos=> f!nction


&he strpos=> f!nction is !se( to search for a character:text within a string. If a "atch is fo!n(5 this f!nction will ret!rn the character position of the first "atch. If no "atch is fo!n(5 it will ret!rn ALSE. Let6s see if we can fin( the string ?worl(? in o!r string9

<?php echo strpos*"Hello =orld#"/"=orld"+; ?>


&he o!tp!t of the co(e abo1e will be9

%
&he position of the string ?worl(? in the exa"ple abo1e is H. &he reason that it is H =an( not N>5 is that the first character position in the string is J5 an( not I.

*o"plete PHP String 2eference


or a co"plete reference of all string f!nctions5 go to o!r co"plete PHP String 2eference. &he reference contains a brief (escription5 an( exa"ples of !se5 for each f!nctionO

PHP Operators
&he assign"ent operator G is !se( to assign 1al!es to 1ariables in PHP. &he arith"etic operator A is !se( to a(( 1al!es together.

Arith"etic Operators
&he table below lists the arith"etic operators in PHP9 /$erator .a)e Descri$tion 01a)$le Result

xAy x,y xRy x:y xSy

A((ition S!btraction M!ltiplication 'i1ision Mo(!l!s

S!" of x an( y 'ifference of x an( y Pro(!ct of x an( y -!otient of x an( y 2e"ain(er of x (i1i(e( by y

PAP C,P CRP IC : C CSP IJ S T IJ S P ,P ?Hi? . ?Ha?

Q @ IJ @ I P J HiHa

,x a.b

Begation *oncatenation

Opposite of x *oncatenate two strings

Assign"ent Operators
&he basic assign"ent operator in PHP is ?G?. It "eans that the left operan( gets set to the 1al!e of the expression on the right. &hat is5 the 1al!e of ?#x G C? is C. Assign)ent Sa)e as222 xGy x AG y x ,G y x RG y x :G y x SG y a .G b xGy xGxAy xGx,y xGxRy xGx:y xGxSy aGa.b Descri$tion &he left operan( gets set to the 1al!e of the expression on the right A((ition S!btraction M!ltiplication 'i1ision Mo(!l!s *oncatenate two strings

Incre"enting:'ecre"enting Operators
/$erator AA x x AA ,, x x ,, .a)e Pre,incre"ent Post,incre"ent Pre,(ecre"ent Post,(ecre"ent Descri$tion Incre"ents x by one5 then ret!rns x 2et!rns x5 then incre"ents x by one 'ecre"ents x by one5 then ret!rns x 2et!rns x5 then (ecre"ents x by one

*o"parison Operators
*o"parison operators allows yo! to co"pare two 1al!es9 /$erator x GG y x GGG y x OG y x EF y .a)e ED!al I(entical Bot eD!al Bot eD!al Descri$tion &r!e if x is eD!al to y 01a)$le CGGT ret!rns false

&r!e if x is eD!al to y5 an( they are of CGGG?C? ret!rns false sa"e type &r!e if x is not eD!al to y &r!e if x is not eD!al to y COGT ret!rns tr!e CEFT ret!rns tr!e

x OGG y xFy xEy x FG y x EG y

Bot i(entical %reater than Less than %reater than or eD!al to Less than or eD!al to

&r!e if x is not eD!al to y5 or they are COGG?C? ret!rns tr!e not of sa"e type &r!e if x is greater than y &r!e if x is less than y CFT ret!rns false CET ret!rns tr!e

&r!e if x is greater than or eD!al to y CFGT ret!rns false &r!e if x is less than or eD!al to y CEGT ret!rns tr!e

Logical Operators
/$erator x an( y .a)e An( Descri$tion &r!e if both x an( y are tr!e 01a)$le xGH yG@ =x E IJ an( y F I> ret!rns tr!e

x or y

Or

&r!e if either or both x an( y are tr!e xGH yG@ =xGGH or yGGC> ret!rns tr!e &r!e if either x or y is tr!e5 b!t not both &r!e if both x an( y are tr!e xGH yG@ =xGGH xor yGG@> ret!rns false xGH yG@ =x E IJ UU y F I> ret!rns tr!e

x xor y

/or

x UU y

An(

x VV y

Or

&r!e if either or both x an( y are tr!e xGH yG@ =xGGC VV yGGC> ret!rns false &r!e if x is not tr!e xGH yG@ O=xGGy> ret!rns tr!e

Ox

Bot

Array Operators
/$erator xAy x GG y x GGG y x OG y x EF y x OGG y .a)e )nion ED!ality I(entity IneD!ality IneD!ality Bon,i(entity Descri$tion )nion of x an( y &r!e if x an( y ha1e the sa"e +ey:1al!e pairs &r!e if x an( y ha1e the sa"e +ey:1al!e pairs in the sa"e or(er an( of the sa"e types &r!e if x is not eD!al to y &r!e if x is not eD!al to y &r!e if x is not i(entical to y

PHP 3f2220lse State"ents


*on(itional state"ents are !se( to perfor" (ifferent actions base( on (ifferent con(itions.

*on(itional State"ents
Very often when yo! write co(e5 yo! want to perfor" (ifferent actions for (ifferent (ecisions. 7o! can !se con(itional state"ents in yo!r co(e to (o this. In PHP we ha1e the following con(itional state"ents9

if state)ent , !se this state"ent to exec!te so"e co(e only if a specifie( con(ition is tr!e if222else state)ent , !se this state"ent to exec!te so"e co(e if a con(ition is tr!e an( another co(e if the con(ition is false if222elseif2222else state)ent , !se this state"ent to select one of se1eral bloc+s of co(e to be exec!te( s itc% state)ent , !se this state"ent to select one of "any bloc+s of co(e to be exec!te(

&he if State"ent
)se the if state"ent to exec!te so"e co(e only if a specifie( con(ition is tr!e.

Syntax i( *condition+ code to be executed if condition is true;


&he following exa"ple will o!tp!t ?Ha1e a nice wee+en(O? if the c!rrent (ay is ri(ay9

<html> <body> <?php $d=date*">"+; i( *$d=="?ri"+ echo "Ha!e a nice =eekend#"; ?> </body> </html>
Botice that there is no ..else.. in this syntax. &he co(e is exec!te( onl* if t%e s$ecified condition is true.

&he if...else State"ent


)se the if....else state"ent to exec!te so"e co(e if a con(ition is tr!e an( another co(e if a con(ition is false.

Syntax i( *condition+ , code to be executed if condition is true; else , code to be executed if condition is false; -

Exa"ple
&he following exa"ple will o!tp!t ?Ha1e a nice wee+en(O? if the c!rrent (ay is ri(ay5 otherwise it will o!tp!t ?Ha1e a nice (ayO?9

<html> <body> <?php $d=date*">"+; i( *$d=="?ri"+ , echo "Ha!e a nice =eekend#"; else , echo "Ha!e a nice day#"; ?> </body> </html>

&he if222elseif2222else State"ent


)se the if....elseif...else state"ent to select one of se1eral bloc+s of co(e to be exec!te(.

Syntax i( *condition+ , code to be executed if condition is true; elsei( *condition+ , code to be executed if condition is true; else , code to be executed if condition is false; Exa"ple
&he following exa"ple will o!tp!t ?Ha1e a nice wee+en(O? if the c!rrent (ay is ri(ay5 an( ?Ha1e a nice S!n(ayO? if the c!rrent (ay is S!n(ay. Otherwise it will o!tp!t ?Ha1e a nice (ayO?9

<html> <body> <?php $d=date*">"+; i( *$d=="?ri"+ , echo "Ha!e a nice =eekend#"; elsei( *$d=="6)n"+ , echo "Ha!e a nice 6)nday#"; else , echo "Ha!e a nice day#"; ?> </body> </html>

PHP S itc% State"ent


*on(itional state"ents are !se( to perfor" (ifferent actions base( on (ifferent con(itions.

&he PHP Switch State"ent


)se the switch state"ent to select one of "any bloc+s of co(e to be exec!te(.

Syntax s=itch *n+ ,

case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; de(a)lt@ code to be executed if n is different from both label1 and label2; &his is how it wor+s9 irst we ha1e a single expression n ="ost often a 1ariable>5 that is e1al!ate( once. &he 1al!e of the expression is then co"pare( with the 1al!es for each case in the str!ct!re. If there is a "atch5 the bloc+ of co(e associate( with that case is exec!te(. )se brea4 to pre1ent the co(e fro" r!nning into the next case a!to"atically. &he (efa!lt state"ent is !se( if no "atch is fo!n(.

Exa"ple <html> <body>


<?php $"=$; s=itch *$"+ , case $@ echo "A)mber $"; break; case ;@ echo "A)mber ;"; break; case B@ echo "A)mber B"; break; de(a)lt@ echo "Ao n)mber bet=een $ and B"; ?> </body> </html>

PHP Arra*s
An array stores "!ltiple 1al!es in one single 1ariable.

What is an Array<
A 1ariable is a storage area hol(ing a n!"ber or text. &he proble" is5 a 1ariable will hol( only one 1al!e. An array is a special 1ariable5 which can store "!ltiple 1al!es in one single 1ariable. If yo! ha1e a list of ite"s =a list of car na"es5 for exa"ple>5 storing the cars in single 1ariables co!l( loo+ li+e this9

$cars$="6aab"; $cars;=" ol!o"; $carsB="4:W";


Howe1er5 what if yo! want to loop thro!gh the cars an( fin( a specific one< An( what if yo! ha( not @ cars5 b!t @JJ< &he best sol!tion here is to !se an arrayO An array can hol( all yo!r 1ariable 1al!es !n(er a single na"e. An( yo! can access the 1al!es by referring to the array na"e. Each ele"ent in the array has its own in(ex so that it can be easily accesse(. In PHP5 there are three +in( of arrays9

.u)eric arra* , An array with a n!"eric in(ex Associative arra* , An array where each I' +ey is associate( with a 1al!e Multidi)ensional arra* , An array containing one or "ore arrays

B!"eric Arrays
A n!"eric array stores each array ele"ent with a n!"eric in(ex. &here are two "etho(s to create a n!"eric array. I. In the following exa"ple the in(ex are a!to"atically assigne( =the in(ex starts at J>9

$cars=array*"6aab"/" ol!o"/"4:W"/"Toyota"+;
P. In the following exa"ple we assign the in(ex "an!ally9

$cars7.9="6aab"; $cars7$9=" ol!o"; $cars7;9="4:W"; $cars7B9="Toyota";

Exa"ple
In the following exa"ple yo! access the 1ariable 1al!es by referring to the array na"e an( in(ex9

<?php $cars7.9="6aab"; $cars7$9=" ol!o"; $cars7;9="4:W"; $cars7B9="Toyota"; echo $cars7.9 < " and " < $cars7$9 < " are 6=edish cars<"; ?>

&he co(e abo1e will o!tp!t9

6aab and

ol!o are 6=edish cars<

Associati1e Arrays
An associati1e array5 each I' +ey is associate( with a 1al!e. When storing (ata abo!t specific na"e( 1al!es5 a n!"erical array is not always the best way to (o it. With associati1e arrays we can !se the 1al!es as +eys an( assign 1al!es to the".

Exa"ple I
In this exa"ple we !se an array to assign ages to the (ifferent persons9

$a'es = array*"Ceter"=>B;/ "D)a'mire"=>B./ "Eoe"=>BF+;

Exa"ple P
&his exa"ple is the sa"e as exa"ple I5 b!t shows a (ifferent way of creating the array9

$a'es78Ceter89 = "B;"; $a'es78D)a'mire89 = "B."; $a'es78Eoe89 = "BF";


&he I' +eys can be !se( in a script9

<?php $a'es78Ceter89 = "B;"; $a'es78D)a'mire89 = "B."; $a'es78Eoe89 = "BF"; echo "Ceter is " < $a'es78Ceter89 < " years old<"; ?>
&he co(e abo1e will o!tp!t9

Ceter is B; years old<

M!lti(i"ensional Arrays
In a "!lti(i"ensional array5 each ele"ent in the "ain array can also be an array. An( each ele"ent in the s!b,array can be an array5 an( so on.

Exa"ple
In this exa"ple we create a "!lti(i"ensional array5 with a!to"atically assigne( I' +eys9

$(amilies = array * "1ri((in"=>array * "Ceter"/ "2ois"/ ":e'an" +/ "D)a'mire"=>array * "1lenn" +/ "4ro=n"=>array * "Cle!eland"/ "2oretta"/ "E)nior" + +;
&he array abo1e wo!l( loo+ li+e this if written to the o!tp!t9

5rray * 71ri((in9 => 5rray * 7.9 => Ceter 7$9 => 2ois 7;9 => :e'an + 7D)a'mire9 => 5rray * 7.9 => 1lenn + 74ro=n9 => 5rray * 7.9 => Cle!eland 7$9 => 2oretta 7;9 => E)nior + +

Exa"ple P
Lets try (isplaying a single 1al!e fro" the array abo1e9

echo "Gs " < $(amilies781ri((in897;9 < " a part o( the 1ri((in (amily?";
&he co(e abo1e will o!tp!t9

Gs :e'an a part o( the 1ri((in (amily?

*o"plete PHP Array 2eference


or a co"plete reference of all array f!nctions5 go to o!r co"plete PHP Array 2eference. &he reference contains a brief (escription5 an( exa"ples of !se5 for each f!nctionO

PHP Looping , 5%ile Loo$s


Loops exec!te a bloc+ of co(e a specifie( n!"ber of ti"es5 or while a specifie( con(ition is tr!e.

PHP Loops
Often when yo! write co(e5 yo! want the sa"e bloc+ of co(e to r!n o1er an( o1er again in a row. Instea( of a((ing se1eral al"ost eD!al lines in a script we can !se loops to perfor" a tas+ li+e this. In PHP5 we ha1e the following looping state"ents9

%ile , loops thro!gh a bloc+ of co(e while a specifie( con(ition is tr!e do222 %ile , loops thro!gh a bloc+ of co(e once5 an( then repeats the loop as long as a specifie( con(ition is tr!e for , loops thro!gh a bloc+ of co(e a specifie( n!"ber of ti"es foreac% , loops thro!gh a bloc+ of co(e for each ele"ent in an array

&he while Loop


&he while loop exec!tes a bloc+ of co(e while a con(ition is tr!e.

Syntax =hile *condition+ , code to be executed; Exa"ple


&he exa"ple below first sets a 1ariable i to I =#iGIW>. &hen5 the while loop will contin!e to r!n as long as i is less than5 or eD!al to C. i will increase by I each ti"e the loop r!ns9

<html> <body> <?php $i=$; =hile*$i<=&+ , echo "The n)mber is " < $i < "<br>"; $i00; ?> </body> </html>
O!tp!t9

The The The The The

n)mber n)mber n)mber n)mber n)mber

is is is is is

$ ; B F &

&he (o...while State"ent


&he (o...while state"ent will always exec!te the bloc+ of co(e once5 it will then chec+ the con(ition5 an( repeat the loop while the con(ition is tr!e.

Syntax do , code to be executed; =hile *condition+; Exa"ple


&he exa"ple below first sets a 1ariable i to I =#iGIW>. &hen5 it starts the (o...while loop. &he loop will incre"ent the 1ariable i with I5 an( then write so"e o!tp!t. &hen the con(ition is chec+e( =is i less than5 or eD!al to C>5 an( the loop will contin!e to r!n as long as i is less than5 or eD!al to C9

<html> <body> <?php $i=$; do , $i00; echo "The n)mber is " < $i < "<br>"; =hile *$i<=&+; ?> </body> </html>
O!tp!t9

The The The The The

n)mber n)mber n)mber n)mber n)mber

is is is is is

; B F & %

&he for loop an( the foreach loop will be explaine( in the next chapter.

PHP Looping , 6or Loo$s


Loops exec!te a bloc+ of co(e a specifie( n!"ber of ti"es5 or while a specifie( con(ition is tr!e.

&he for Loop


&he for loop is !se( when yo! +now in a(1ance how "any ti"es the script sho!l( r!n.

Syntax (or *init; condition; increment+ , code to be executed; Para"eters9

init9 Mostly !se( to set a co!nter =b!t can be any co(e to be exec!te( once at the beginning of the loop>

condition9 E1al!ate( for each loop iteration. If it e1al!ates to &2)E5 the loop contin!es. If it e1al!ates to ALSE5 the loop en(s. increment9 Mostly !se( to incre"ent a co!nter =b!t can be any co(e to be exec!te( at the en( of the iteration>

.ote- &he init an( increment para"eters abo1e can be e"pty or ha1e "!ltiple expressions =separate( by co""as>.

Exa"ple
&he exa"ple below (efines a loop that starts with iGI. &he loop will contin!e to r!n as long as the 1ariable i is less than5 or eD!al to C. &he 1ariable i will increase by I each ti"e the loop r!ns9

<html> <body> <?php (or *$i=$; $i<=&; $i00+ , echo "The n)mber is " < $i < "<br>"; ?> </body> </html>
O!tp!t9

The The The The The

n)mber n)mber n)mber n)mber n)mber

is is is is is

$ ; B F &

&he foreach Loop


&he foreach loop is !se( to loop thro!gh arrays.

Syntax (oreach *$array as $value+ , code to be executed; or e1ery loop iteration5 the 1al!e of the c!rrent array ele"ent is assigne( to #1al!e =an( the array pointer is "o1e( by one> , so on the next loop iteration5 yo!6ll be loo+ing at the next array 1al!e.

Exa"ple
&he following exa"ple (e"onstrates a loop that will print the 1al!es of the gi1en array9

<html> <body> <?php $"=array*"one"/"t=o"/"three"+; (oreach *$" as $!al)e+ , echo $!al)e < "<br>"; ?> </body> </html>
O!tp!t9

one t=o three

PHP 6unctions
&he real power of PHP co"es fro" its f!nctions. In PHP5 there are "ore than NJJ b!ilt,in f!nctions.

PHP .!ilt,in !nctions


or a co"plete reference an( exa"ples of the b!ilt,in f!nctions5 please 1isit o!r PHP 2eference.

PHP !nctions
In this chapter we will show yo! how to create yo!r own f!nctions. &o +eep the script fro" being exec!te( when the page loa(s5 yo! can p!t it into a f!nction. A f!nction will be exec!te( by a call to the f!nction.

7o! "ay call a f!nction fro" anywhere within a page.

*reate a PHP !nction


A f!nction will be exec!te( by a call to the f!nction.

Syntax ()nction functionName*+ , code to be executed; PHP f!nction g!i(elines9

%i1e the f!nction a na"e that reflects what the f!nction (oes &he f!nction na"e can start with a letter or !n(erscore =not a n!"ber>

Exa"ple
A si"ple f!nction that writes "y na"e when it is calle(9

<html> <body> <?php ()nction =riteAame*+ , echo "Hai Eim Ie(snes"; echo ":y name is "; =riteAame*+; ?> </body> </html>
O!tp!t9

:y name is Hai Eim Ie(snes

PHP !nctions , A((ing para"eters


&o a(( "ore f!nctionality to a f!nction5 we can a(( para"eters. A para"eter is ;!st li+e a 1ariable.

Para"eters are specifie( after the f!nction na"e5 insi(e the parentheses.

Exa"ple I
&he following exa"ple will write (ifferent first na"es5 b!t eD!al last na"e9

<html> <body> <?php ()nction =riteAame*$(name+ , echo $(name < " Ie(snes<<br>"; echo ":y name is "; =riteAame*"Hai Eim"+; echo ":y sister8s name is "; =riteAame*"He'e"+; echo ":y brother8s name is "; =riteAame*"6tale"+; ?> </body> </html>
O!tp!t9

:y name is Hai Eim Ie(snes< :y sister8s name is He'e Ie(snes< :y brother8s name is 6tale Ie(snes<

Exa"ple P
&he following f!nction has two para"eters9

<html> <body> <?php ()nction =riteAame*$(name/$p)nct)ation+ , echo $(name < " Ie(snes" < $p)nct)ation < "<br>"; echo ":y name is "; =riteAame*"Hai Eim"/"<"+; echo ":y sister8s name is "; =riteAame*"He'e"/"#"+;

echo ":y brother8s name is "; =riteAame*"6tJle"/"?"+; ?> </body> </html>


O!tp!t9

:y name is Hai Eim Ie(snes< :y sister8s name is He'e Ie(snes# :y brother8s name is 6tJle Ie(snes?

PHP !nctions , 2et!rn 1al!es


&o let a f!nction ret!rn a 1al!e5 !se the ret!rn state"ent.

Exa"ple <html> <body>


<?php ()nction add*$"/$y+ , $total=$"0$y; ret)rn $total; echo "$ 0 $% = " < add*$/$%+; ?> </body> </html>
O!tp!t9

$ 0 $% = $K

PHP 6or)s and 7ser 3n$ut


&he PHP #$%E& an( #$POS& 1ariables are !se( to retrie1e infor"ation fro" for"s5 li+e !ser inp!t.

PHP or" Han(ling


&he "ost i"portant thing to notice when (ealing with H&ML for"s an( PHP is that any for" ele"ent in an H&ML page will auto)aticall* be a1ailable to yo!r PHP scripts.

Exa"ple
&he exa"ple below contains an H&ML for" with two inp!t fiel(s an( a s!b"it b!tton9

<html> <body> <(orm action="=elcome<php" method="post"> Aame@ <inp)t type="te"t" name="(name"> 5'e@ <inp)t type="te"t" name="a'e"> <inp)t type="s)bmit"> </(orm> </body> </html>
When a !ser fills o!t the for" abo1e an( clic+s on the s!b"it b!tton5 the for" (ata is sent to a PHP file5 calle( ?welco"e.php?9 ?welco"e.php? loo+s li+e this9

<html> <body> Welcome <?php echo $LC36T7"(name"9; ?>#<br> Mo) are <?php echo $LC36T7"a'e"9; ?> years old< </body> </html>
O!tp!t co!l( be so"ething li+e this9

Welcome Eohn# Mo) are ;N years old<


&he PHP #$%E& an( #$POS& 1ariables will be explaine( in the next chapters.

or" Vali(ation
)ser inp!t sho!l( be 1ali(ate( on the browser whene1er possible =by client scripts>. .rowser 1ali(ation is faster an( re(!ces the ser1er loa(. 7o! sho!l( consi(er ser1er 1ali(ation if the !ser inp!t will be inserte( into a (atabase. A goo( way to 1ali(ate a for" on the ser1er is to post the for" to itself5 instea( of ;!"ping to a (ifferent page. &he !ser will then get the error "essages on the sa"e page as the for". &his "a+es it easier to (isco1er the error.

PHP 89:0T Variable


In PHP5 the pre(efine( #$%E& 1ariable is !se( to collect 1al!es in a for" with "etho(G?get?.

&he #$%E& Variable


&he pre(efine( #$%E& 1ariable is !se( to collect 1al!es in a for" with "etho(G?get? Infor"ation sent fro" a for" with the %E& "etho( is 1isible to e1eryone =it will be (isplaye( in the browser6s a((ress bar> an( has li"its on the a"o!nt of infor"ation to sen(.

Exa"ple <(orm action="=elcome<php" method="'et"> Aame@ <inp)t type="te"t" name="(name"> 5'e@ <inp)t type="te"t" name="a'e"> <inp)t type="s)bmit"> </(orm>
When the !ser clic+s the ?S!b"it? b!tton5 the )2L sent to the ser1er co!l( loo+ so"ething li+e this9

http@//===<=Bschools<com/=elcome<php?(name=CeterOa'e=BK
&he ?welco"e.php? file can now !se the #$%E& 1ariable to collect for" (ata =the na"es of the for" fiel(s will a!to"atically be the +eys in the #$%E& array>9

Welcome <?php echo $L1PT7"(name"9; ?><<br> Mo) are <?php echo $L1PT7"a'e"9; ?> years old#

When to !se "etho(G?get?<


When !sing "etho(G?get? in H&ML for"s5 all 1ariable na"es an( 1al!es are (isplaye( in the )2L. .ote- &his "etho( sho!l( not be !se( when sen(ing passwor(s or other sensiti1e infor"ationO

Howe1er5 beca!se the 1ariables are (isplaye( in the )2L5 it is possible to boo+"ar+ the page. &his can be !sef!l in so"e cases. .ote- &he get "etho( is not s!itable for 1ery large 1ariable 1al!es. It sho!l( not be !se( with 1al!es excee(ing PJJJ characters.

PHP 89P/ST !nction


In PHP5 the pre(efine( #$POS& 1ariable is !se( to collect 1al!es in a for" with "etho(G?post?.

&he #$POS& Variable


&he pre(efine( #$POS& 1ariable is !se( to collect 1al!es fro" a for" sent with "etho(G?post?. Infor"ation sent fro" a for" with the POS& "etho( is in1isible to others an( has no li"its on the a"o!nt of infor"ation to sen(. .ote- Howe1er5 there is an T M. "ax si4e for the POS& "etho(5 by (efa!lt =can be change( by setting the post$"ax$si4e in the php.ini file>.

Exa"ple <(orm action="=elcome<php" method="post"> Aame@ <inp)t type="te"t" name="(name"> 5'e@ <inp)t type="te"t" name="a'e"> <inp)t type="s)bmit"> </(orm>
When the !ser clic+s the ?S!b"it? b!tton5 the )2L will loo+ li+e this9

http@//===<=Bschools<com/=elcome<php
&he ?welco"e.php? file can now !se the #$POS& 1ariable to collect for" (ata =the na"es of the for" fiel(s will a!to"atically be the +eys in the #$POS& array>9

Welcome <?php echo $LC36T7"(name"9; ?>#<br> Mo) are <?php echo $LC36T7"a'e"9; ?> years old<

When to !se "etho(G?post?<

Infor"ation sent fro" a for" with the POS& "etho( is in1isible to others an( has no li"its on the a"o!nt of infor"ation to sen(. Howe1er5 beca!se the 1ariables are not (isplaye( in the )2L5 it is not possible to boo+"ar+ the page.

&he PHP #$2E-)ES& Variable


&he pre(efine( #$2E-)ES& 1ariable contains the contents of both #$%E&5 #$POS&5 an( #$*OO8IE. &he #$2E-)ES& 1ariable can be !se( to collect for" (ata sent with both the %E& an( POS& "etho(s.

Exa"ple Welcome <?php echo $LIPDQP6T7"(name"9; ?>#<br> Mo) are <?php echo $LIPDQP6T7"a'e"9; ?> years old<

You might also like