Learning PHP - The Beginners Guide to Web Development

Page 1

UMICITY.COM

THE BEGINNERS GUIDE TO E-WOLRD

Video Tutorials Available in Umicity www.umicity.com

Learning PHP |Ahmed Sammy Hegab| Š 2008 Umicom Group Plc


Introduction This course is part of the beginners guide to e-business, a comprehensive step by step course with accompanying video tutorials for anyone interested in Web Development, Internet Sales/Marketing, Computerised Accounting, and finally for anyone who aspires to Setting up and run a successful online business. 1.

Starting with web development topics Learning HTML Learning XML Learning CSS Learning JavaScript Learning PHP & MYSQL Learning Smarty Template Engine Learning CodeIgniter Framework: Learning Facebook Application Development Learning UmiCity Application Development

We will also explore the world of Open Source, looking at all the common script like shopping carts, blogs, Forums, Content Management Systems (CMS) and much more .. 2.

Business Application topics • Learning MS Office • Learning Sage Line 50 Financial Controller 2008

3.

Online Sales & Marketing topics • Learning Search Engine Marketing • Learning Online Revenue Channels • Learning Social Networking • Learning Multi Level Marketing (MLM)

4.

Business Start-up topics • Learning Business Start-up Foundation o Registering a company o Inland Revenue, Taxation and National Insurance o Setting up a business bank account o Setting up PayPal accounts and Merchant Accounts o Office leasing, virtual office and hot desking o Telecommunication and internet service providers o Registering Domain name and hosting • Learning Business Planning o Market Research o Cash Flow Forecast o Break even Analysis & pricing o Business plan write up • Learning Business Funding o Share issue and allocation o Bartering

[Type text]

Page 2


Pre Hypertext pre-Processor (PHP) Course Lesson 1 - Video lessons available on www.umicity.com What is PHP? PHP known as hypertext pre-processor evolved from the personnel home page tools created by Rasmus Lerdorf simply to track users accessing his website. Since PHP is open source language developers around the world began contributing ideas and by 1997 over 50,000 websites were using php Andi Gutmans and Zeev Suraski took php to the next level by creating an Application Programming Interface (API) which was released in 1998 as php3 In 1999 the updated version of php4 incorporated Zend engine which allows PHP scripting to be used with any combination of web server operating system and platforms. PHP5 was released in 2005 incorporating better security features and adds support for XML and Object-Oriented Programming (OOP) Now PHP is used in over 16 million web sites worldwide. What is the use of PHP? With php we can read, write files, gather and process form data, send data via email, access and manipulate database records, read and write cookies, maintain data in session variables, facilitate user authentication and much more... How does PHP work? When a web browser requests a php page from a web server, the server responds by calling up the PHP parser to process all the PHP elements. The PHP parser executes the PHP script instructions on the page, generating HTML documents that are then sent to the user browser. PHP parser may also retrieve or manipulate a database. What do we need to get started in PHP? For us to develop php websites we must have six key components: 1. Text Editor -Firstly and most obvious we need a text editor to type the PHP script, there are many in the market for free. The one we will make use of in this course is Text-Edit, which you can download for free http://www.freesoftwarehouse.com 2. Web Server – PHP works with all web servers including Microsoft Internet Information Server (IIS), most commonly PHP is used with Apache Server, which is an open source free web server. 3. Server Operating System - Most web servers are pre-installed with Linux platform, which provides the reliability needed for minimum downtime and has robust security. 4. PHP Parser – A parser must be installed on your web server to generate HTML output on the fly. 5. Database – PHP works with all database software, including Oracle, Sybase and MS Sql, but it is most often used with the free open source MySQL database software. 6. FTP Client – To upload the scripts to our web server we need to use FTP, you can do this from windows or you can download any FTP client applications for free or for a nominal fee. In this course we will make use of CuteFTP 8 by GlobalScape which we feel is one of the best available FTP applications. Download it for a free 30 day trail. The acronym “LAMP” is often used to describe the typical server configuration (Linux, Apache, MySQL and PHP).

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 3


Pre Hypertext pre-Processor (PHP) Course Lesson 2 Syntax Rules In PHP the statements can be in uppercase or lowercase and they would still work, however variables such as “name” & “Name” would be two different variables How do we start a PHP script? <? Opens the PHP tag similarly when starting HTML we start with the opening <HTML> Tag We close a PHP code with ?> We can open and close a PHP code several times in the script by applying the correct open <? And close ?> tags. It might be useful to know that when you start an ASP script it is very similar except we use <% and we close %>

Language Mix We can mix a php code within HTML, JavaScript, Smarty Template engine but it should all be clearly marked and the appropriate tags must be placed correctly

Comments To make comments in PHP we have three options we can use Line comments // this is a line comment # This is another example of a line comment Comments on several lines /* This is a block comment And can be on several lines All will be ignored till we reach The end of the comment */ Printing to screen We can use the echo function to print a statement to screen, for example Example 1: helloworld.php <html> <head><title> My first PHP script : by Ahmed Sammy Hegab</title><head> <body> <? echo “ My Name is Ahmed Sammy Hegab, Hello World! <br>”; ?> </body> </html>

[Type text]

Page 4


Escape Characters Just like in C programming we have an escape character, PHP is very common in C programming in much of its syntax and we will find “\” backslash to be used to escape the effect of quotation marks which is usually read as the start and end of a string. Variables Variables are used to store data for manipulation within the program. Variables are a common component in programming in general the syntax varies from PHP and C programming. In PHP all variables start with the dollar ‘$’ character and unlike C programming we do not need to specify the type, it simply takes any form we give it. I.e. Text, integer, float, array etc.. As you will see in the example below we will assign a HTML string Example 2: myvariable.php <html> <head><title>My Variable Example: By Ahmed Sammy Hegab</title></head> <body> <h3> Example of Variable holding HTML content </h3> // this is a comment and will be ignored by the parser <? $str =”<textarea rows=\”5\” cols=\”48\”>\”Utinam populus Romanus Unam Cervicem haberet!\” \n (Would that the roman people had but one neck!) \n \n \t \t\t Caligula A.D. 12-41 </textarea>”; echo ($str); ?> </body> </html>

Data Types We can have different data types and we will cover some basic types here String – Strings of spaces, text and numberica characters within double or singel quotes Integer – numbers without decimal places like 1,2,3,4,5 Floating point – numbers with decminal places 3.142 Boolean – True or Flase Yes or No Null – No Value Example 3: myvar2.php <? $str=”here is a string”; $int=77; Echo “string: $str<br>”; Echo “integer: $int <br>”); Echo “floating point number: $flt <br>”; Echo “null: $non”; ?>

$flt=3.142;

$non= null;

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 5


Re-using Variables A variable can be redefined at any point in the script try the example below Example 4: mycheese.php <? $cheese =”chedder”; ?> <b> I like </b> <? echo $cheese; ?> <br/> <? $cheese =”Stilton”; ?> <i> I also like </i> <? echo $cheese; ?>

A quite note worth mentioning here we do not need to place quotes around variables, however when we are outputting text and variables in the same line of code we can either use concatination or place it all within double quotes. Using single quotes wont show the value of the variable but just display the variable name. Concatentaion We use concatenation to add data to a string or to tag several variables together to output let us do a quick example to illustrate concatentaion as we will use this property quite frequently. Example 5: Concat.php <? $string1=”concat”; $string2=”enation”; $string3=$string1.$string2; echo $string3; // another alternative way to concatination ?> <br> <br> <? $string1 =”con”; $string1 .=”cat”; $string1 .=”enation”; echo $string1; ?>

[Type text]

Page 6


Pre Hypertext pre-Processor (PHP) Course Lesson 3 In this lesson we will go over some fundamental basics in PHP, such as Arthmatical and Logical Operators, which we will need for the next series of lessons Arithmetical operators + Addition . String concatenation - Subtraction * Multiplication / Division % Modulus ++ Increment ‘- -‘ Decrement Logical operators && Logical AND And Logical AND || Logical OR Or Logical OR Xor Logical exclusive XOR ! Logical NOT Assignment operators Operator = += .= -= *= /= %=

Example $a = $b $a += $b $a .= $b $a -= $b $a *= $b $a /= $b $a %= $b

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Equivalent $a = $b $a = $a + $b $a = $a . $b $a = $a - $b $a = $a * $b $a = $a / $b $a = $a % $b

Page 7


Example 1: mathsandLogic.php <html><head><title> Arithmetical & Logical Operators example: by Ahmed Sammy Hegab</title></head> <body><? $a=true; $b=false; $addnum=20+30; $addstr=”I Love”.” PHP”; $sub = 35.75 – 28.25; $mul = 8*50; $mod = 65 % 2; $inc=5; $dec=5; ++$inc; --$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>”; ?> <h3> <? Echo $result; ?></h3> <? # Test both variable operands for true if we recall we assigned $a=true and $b=false # below we use the logical operators to test for true. $test1 =($a and $a)?”true”:”false”; /* this is a shorthand test for if ($a=true and $a=true) { $test1=true; } else { $test1=false; } We will cover If & Else statements but for now we are quickly making use of this shorthand statment also known in PHP as a CASE statement *** Please note this is an example of a comment and this entire block will be ignored by the server */ $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”; // We will reuse the result variable to insert the new results // from the above logical operation tests ** note this is a comment and will be ignored $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>”; ?> <h3><? echo $result; ?></h3></body></html>

[Type text]

Page 8


Condition IF Statements We converted briefly a condition statement knowns as the turnary operator in the above example, however now we will start the condition statement topics by introducing you to the IF statement, If else, Else, the turnary operator and finally switch, case statement. The syntax of an If statement is If (test expression) {statement to execute when true} Example 2: ifcondition.php <? $age=32; Echo “you are $age year”; If ($age > 1) { Echo “s”; } Echo “ old”; ?>

If –Else & if-elseif Statement Sytax If (test-expression) {do this} else { do this } If (test-expression) {do this} elseif { do this } else {do this} Also a more simplified syntax for if and else statement could also be written as this If (test expression) do this; Elseif do this; We will do an example to illustrate if and else condition Example 3: ifelsecon.php <html> <head><title>If-Else Statement</title></head> <body> <? $num=2; $bool=false; If ($num==1 and $bool==true) echo “test 1 success”; elseif($num==2 and $bool==true) echo “test 2 success”; elseif($num==2 and $bool==false) echo “test 3 success”; elseif($num==3 and $bool==false) echo “test 4 success”; ?> </body> </html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 9


Switch statement Switch can be useful also in some occations and we will do an example to illustarate Example 4: switchcondition.php <html> <head><title> Switch Statement: by Ahmed Sammy Hegab</title></head> <body> <? $num=2; Switch ($num) { Case 1: echo (“This is case 1 code”); break; Case 2: echo (“this is case 2 code”); break; Case 3: echo (“This is case 3 code”); break; Default: echo (“this is default code”); } ?> </body> </html>

For loop The for loop is probably the most used type of loop in programming in general and it has the following syntax For (initialiser, test, increment) { Statements } Example 5: forcondition.php <html> <head><title> For loop</title></head> <body> <? $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”); ?> </body> </html>

[Type text]

Page 10


While loop While loop is also a common loop type below is an example which we will explain more in the video tutorials Example 6: Whileloop.php <html> <head><title>While loop</title></head> <body> <? $i=0; $num=50; While ($i<10) { $num--; $i++; } echo “Loop stopped at $i<br> \$num is now $num”; ?> </body> </html>

Do-While Loop Example 7: Dowhileloop.php <html> <head><title>Do-While Loop</title></head> <body> <? $i=0; $num=50; Do { $num--; $i++; } While ($i <1); Echo (“loop stopped at $i<br> \ $num is now $num”); ?> </body> </html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 11


Interrupting loops The PHP “break” keyword is used to terminate the excution of a loop prematurely Example 8: Breakstate.php <html> <head><title>Break Statement</title></head> <body> <? $i=0; While ($i<6) { If ($i==3) break; $i++; } echo “Loop stopped at $i by break statement”; ?> </body> </html>

The PHP “continue” keyword is used to halt the currrent iteration of a loop, but it does not terminate the loop. Example 9: Continuestate.php <html> <head><title> Continue Statement</title></head> <body> <? $i=0; $passes=””; While ($i<5) { $++; If ($i==3) continue; $passes =”$i”; } echo “loop stopped at $i<br>”; echo “Completed iterations: $passes”; ?> </body> </html>

[Type text]

Page 12


Pre Hypertext pre-Processor (PHP) Course Lesson 4 In this lesson we will spend this whole lessons on arrays Arrays Numerically indexed Array, count function, sort & rsort Associative Array, each function, each function in while loop, list function Multi-Dimensional Array Creating Array An array is a variable that can contain multiple values, unlike a regular variable that contains only a single value. Example <? $arr=array(); $arr[0]=”First”; $arr[1]=”PHP”; $arr[2]=”array”; $mo=array(“Jan ”,”Feb ”,”Mar ”); $dy=array(“21 ”,”22 ”,”23 ”); $yr=array(“2005”,”2006”,”2007”); echo $arr[0].$arr[1].$arr[2].”<br>”; echo “<br>”.$mo[1].$dy[0].$yr[1]; ?> Changing array element Values Example <html> <head><title>Changing array values</title></head> <body> <? #create an array containing 3 strings $arr=array(“Red”, “Green”, “Blue”); echo $arr[0].$arr[1].$arr[2].”<hr>”; #assign new numeric values $arr[0]=44; $arr[1]=12.5; $arr[2]=$arr[0]+$arr[1]; echo “$arr[0]+$arr[1]=$arr[2]”; ?> </body> </html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 13


Listing array elements Retrieving all elements values from an array is easy with the PHP foreach() function. Which loops through each element of an array. Syntax Foreach (array as variable) { current_variable_value } Example <html> <head><title>List array values</title></head> <body><ol> <? $arr=array(“Red”,”Green”,”Blue”,”Cyan”,”Magenta”,”Black”,”Yellow”); Foreach($arr as $value) { Echo (“<li> Do you like $value? </li>”); } ?> </ol> </body> </html>

Getting the array size Example <html> <head><title>Getting Array Size</title></head> <body><ul> <? $arr=array(); #assign three element values For($i=0; $i<3; $i++) { $arr[$i]=”<li> This is element $i </li>”; } Foreach ($arr as $value) { Each($value); } #assign the number of array elements $size = count ($arr); Echo (“<li> Total number of elements is $size </li>”); ?> </ul> </body> </html>

[Type text]

Page 14


Adding & removing array elements Additional elements can be created at the beginning of an array using the array_unshift() Function, and elements can be added at the end of an array with the array_push() function. <html> <head> <title> Adding array elements </title></head> <body><ol> <? $arr = array(“Red “, “Green “, “Blue”); #add elements at beginning of the array Array_unshift($arr, “Cyan”, “Magenta”); #add elements at end of the array Array_push ($arr, “yellow”, ”black”); #write out each element Foreach ($arr as $value) { Each (“<li> Do you like $value? </li>”); } ?> </ol> </body> </html> The following example removes the first and last elements from an array, then sorts the remaining elements into alphabetical order using the PHP sort() function Example <html><head><title>Remove array elements</title></head> <body> <ol> <? #create an array containing 5 strings $arr=array(“orange”,”Cherrt”,”Apple”,”Banana”,”Lemon”); #remove element at beginning of the array $first=array_shift($arr); #remove element at end of the array $last=array_pop($arr); #sort elements alphabetically Sort($arr); #write out values Foreach ($arr as $value) { echo ($value, “); } Echo (“<br> Removed first element: $first”); Echo (“<br> Removed last element: $last”); ?> </ol></body> </html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 15


Array Keys and Values Instead of a single data value each array element can contain a key value pair Example <html> <head><title>Key-Value array elements</title></head> <body> <ol> <? $arr=array(‘Version’=>10,’OS’=>”Mandrake”,’os’=>”Linux”); Echo “platform: “.$arr[‘OS’].$arr[‘os’].$arr[‘version’]); ?> </ol> </body> </html> Manipulating arrays PHP arrays can be easily manipulated by the many special array functions. The array_merge() function allows two arrays to be merged Example <html> <head><title>Manipulating arrays</title></head> <body><ol> <? $arr1=array(“Alpha”,”Bravo”,”Charlie”); $arr2=array(“Delta”,”Echo”,”Foxtrot”); $arr=array_merge($arr1,$arr2); Foreach($arr as $value) { Echo $value; } Echo(“<hr>”); $arr=array_slice($arr,1,4); Foreach($arr as $value) { Echo $value; } Echo “<hr>”; Srand ((float) microtime()*1000000); Shuffle($arr); Foreach($arr as $value) { Echo $value; } ?> </ol> </body> </html>

[Type text]

Page 16


Example 1: numarray.php <? $beatles = array (“Lennon”, “McCarthey”, “Harrisson”, “starr”); each $beatles[0]; ?>

Numerically indexed array-for loop Example 2: numindexarray.php <? $albums= array(“Please please me”, “sgt peper’s”, “Let it be”, “Help!”); For ($i=0; $i<4; $i++) { Echo “Album no. ”.$i.”is”.$albums[$i].”<br>”; } ?>

Count() Function We can also use the count function to determine the size of the array replace the for condition in the above example with the statement below. For ($i=0; $i<count($albums); $i++) { ... } Sort() Function In the previous example assuming we wanted to sort the array in Alphabetical order. Add this line below the array declaration and above the for loop statement. Sort($albums); Rsort() function In the situation where we want to sort the array in revese we simply use rsort() function. Rsort($albums) Adding to array Example (using count function) Example 3: countfunarray.php <? $numbers=array(“one”,”two”,”three”); $numbers[3]=”four”; For($i=0; $i<count($numbers); $i++) { echo $numbers[$i]; } ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 17


Associative Arrays The associative array is similar to a numerical array but with key words referencing the array value. We see this in the example below: Example 4: AssociativeArray.php <? $greeting=array(“English”=>”hi There”, “French”=”Salut”,”Spanish”=>”Digame”); echo $greetings[“French”]; ?>

Each() function If we wanted to print all the greetings we can use the each function. Replace the echo statement in the above example with $currentgreeting=each ($greetings); Echo $currentgreeting[“key”].”<br>”; Echo $currentgreeting[“value”]; Using while loop with each function Replace the above step with the following code While ($currentgreeting=each($greetings)) { Echo $currentgreeting[“key”].”<br>”; Echo $currentgreeting[“value”].”<br>”; } List Function To Seperate the two components of the Associative array into two meaningful variables we can either assign the key value to a variable called language and the value to a variable called greeting or we can use a built in function called list Replace the previous steps with this new while loop code block. While (list ($language, $greeting)= each ($greetings)) { Echo “In”.$language.”, We say “.$greeting.”<br>”; } Ksort() Function This can be used to sort the key values of the array in alphaptical order. Ksrt($greetings); for reverse it would be krsort($greetings); asort() function To sort the value associated with the key in the array we use asort function. asort($greetings); For reverse arsort($greetings);

[Type text]

Page 18


Adding to an associative array Simple for the previous example add the following statement. $greeting[“Bangali”]=”Ki Khobor”; $greetings[“Arabic”]=”Salam Alykum”; $greetings[“Hebrew”]=”Shalom”; Multi-Dimentional Array: 2D Array A multidimentional array is simply array within array, we will do an example for a 2D then 3D Array. Example 5: 2darray.php <? $books = array(array (array (“The Time Machine”, “Frankenstein”, “Dracula”), array(“Quick and Easy Recipes”, “Fodor’s Guide to Japan”) ); Echo $books[0][1]; ?>

Multi-Dimensional Array: 3D Array Example 6: 3darray.php <? $books=array(array(array(“The Time Machine”, “Dune”, “Do Robots Dream of Electric Sheep?”), Array(“Frankenstin”,”Dracula”)), Array(“Quick and Easy Recipes”, “Fodor’s Guide to Japan”)); Echo $books[0][]0][2]; ?>

Multi Dimensional Associative Array Using Associative Arrays gives a more meaningful key to the echo statment lets do the following example together. Example 7: multiassociativearray.php <? $books=array(“Fiction”=>array(“sci Fi”=>array(“The Time Machine”,”Dune”,”Do Robots Dream of Electric Sheep?”),”Horror”=>array(“Frankenstein”,”Dracula”)), “non fiction”=>array(“Quick ana Easy recipes”, “fodor’s Guide to Japan”)); echo $books[“fiction”][“horror”][1]; ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 19


Summary An array is a set of variables linked together for some common purpose for instance, an array $vital_stats might contain the elements ‘height’, ‘weight’,’hair_clour’ and ‘shoe_size’. Each element is actually a pair a value and a key which is used to refer to the value. By default, the keys are a numbered index starting at zero, but they can also be named for easier reference. Example $vital_stats=array(185, 155, “black”, 42); If we want to give the keys some nice memorable names, use the special operator => like this $vital_stats=array(“height”=>185, “weight”=>155,”hair-colour”=>”black”, “shoe-size”=>42); In a numeric indexed array we can draw data like this. $vital_stats[1]; This would output the weight as arrays start at 0,1,2,3 so [1] is the second element in the array. If it was a named array. We can extract the weight like this $vital_stats[‘weight’]

[Type text]

Page 20


Pre Hypertext pre-Processor (PHP) Course Lesson 5 Functions A function is a piece of PHP code that can be executed once or many times by the PHP script Functions and Variables form the basis of all PHP scripts PHP as we have seen has many inbuilt functions such as echo(), you can also create your own using function keyword in a declaration. Example 1: Functionexample.php <html> <head><title>PHP Function: by Ahmed Sammy Hegab</title></head> <body> <? Function go() { Echo “PHP adds dynamic content <hr><br>”; } ?> <p> *** HTML is Great for <b>static</b> content *** </p> <? go(); ?> </body> </html>

Function Arguments The plain brackets that follow all function names can be used to provide data for use in the code to be executed by that function, just as the brackets of the PHP echo() function contain the string that is to be written in the general pair. The data contained within the brackets is known as the function “argument”.

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 21


Example 2: Functionarg.php <html> <head> <title> PHP Function Arguments </title> </head> <body> <? Function go($arg) { Echo”<b><u><i>$arg</i></u></b>”; } ?> <p> This is the regular text style of this page </p> <? go(“this text has added style”); ?> <p> This is the regular text style of this page </p> <? go(“PHP makes this so easy”); ?> </body> </html> Multiple Functions PHP functions may call other functions during the execution of their code in just the same way that the previous examples called the echo() function. Example 3: functioncall.php <? Function show_numer($num) { $new_numer=make_double($num); Echo(“The Value is $new_number”); } Function make_double($arg) { Return $arg+arg; } ?> <html> <head><title> PHP multiple Functions Call Example: Ahmed Sammy Hegab</title></head> <body> <h3> <? Show_number(4); ?> </h3> </body> </html>

[Type text]

Page 22


Variable Scope Global means the variable can be accessed anywhere in the script local variables can only be accessed in the area they are declared for example if we declare a variable in a function. By default it is a local variable and we can not use it outside the function Global allows us to use the variable outside maybe in another function. Example below experiment around to see if it would work with local variables <? $num; Function make_triple($arg) { Global $num; $num=$arg+$arg+arg; Thrice(); } Function thrice() { Global $num Echo “The Value is $num�; } ?> <html> <head><title>Variable Scope</title> </head> <body> <h3> <? make_triple(4); ?> </h3></body></html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 23


Arrays as arguments Example: functionarray.php <? Function describe_fruit($fruit) { Echo “The $fruit[0] is $fruit[1] and $fruit[2].”; } $banana=array(“banana”,”crescent_shaped”,”yellow”); $apple=array(“apple”,”round”,”green”); $fruit=$apple; describe_fruit($$fruit); Function quote($materials, $time) { Return ($materials *2)+($time*12.75); } Function say_hi() { Echo “Hi There!”; } <? Say_hi(); $t=3; $m=25.95; Echo “<p> Based on our estimates of time and materials, the job will cost £”; Echo quote($m, $t); ?> Multiple arguments Function may specify multiple arguments within their plain brackets to allow several values to be passed to the function code. Example <? Function addup($a=32, $b=32, $c=32) { $total=$a+$b+$c; echo “$a+$b+$c=$total”; } ?> <html> <head><title>Function Arguments</title></head> <body> <h3> <? addup(8,16,24); ?> </h3></body></html>

[Type text]

Page 24


Function with default values Example: defaultfunction.php <? Function addvat($total, $rate=17.5) { $total +=$total*($rate/100); Return $total; } Echo “<p> Total including discounted VAT=£”.addvat(150,5.5); Echo”<p> Total including normal VAT= £”.addvat(150); ?> Example:filetests.php We need to first create a text file called text.txt and place it in the server along with the php script. <? $file=”test.txt”; outfileTestInfo($file); function outputfiletestInfo($f) { if (!file_exists($f)) { echo “<p>$f does not exist</p>”; return; } Echo “<p>$f is “.(is_file($f)?” “:”not “).” a file</p>”; Echo “<p>$f is “.(is_dir($f)?” “:”not “).”a directory</p>”; Echo “<p>$f is “.(is_readable($f)?” “:”not “).”readable</p>”; Echo “<p>$f is “.(is_writable($f)?” “:”not “).”writable</p>”; Echo “<p>$f is “.(is_executable($f)?” “:”not “).”executable</p>”; Echo “<p>$f is “.(filesize($f)).” Bytes</p>”; Echo “<p>$f was accessed on “.date(“D d M Y g:i A”, fileatime($f)).”</p>”; Echo “<p>$f was modified on “.date(“D d M Y g:i A”,filemtime($f)).”</p>”; Echo “<p>$f was changed on “.date(“D d M Y g:i A”, filectime($f)).”</p>”; } ?> Creating and Deleting Files If a file does not exist, we can create it with the touch() function. Given a string representing a file path, touch() attempts to create an empty file of that name. If the file already exists, its contents won’t be disturbed, but the modification date will be updated to reflect the time at which the function executed. Touch(“myfile.txt”); We can remove an existing file with the unlink() function. As did the touch() function, unlink() accepts a file path: Unlink(“myfile.txt”);

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 25


All functions that create, delete, read, write, and modify files on Unix systems require the correct file or directory permissions to be set. Opening a File for Writing, Reading , or Appending Before you can work with a file, you must first open it for reading, writing, or to perform both tasks. PHP provides the fopen() function for doing so, and this function requires a string that contains the file path, followed by a string that contains the mode in which the file is to be opened. The most common modes are read(r), write(w), and append(a). The fopen() function returns a file resource you’ll use later to work with the open file. To open a file for reading, you use the following: $fp=fopen(“text.txt”,”r”); You use the following to open a file for writing: $fp=fopen(“test.txt”,”w”); To open a file for appending (that is, to add data to the end of a file), you use this: $fp=fopen(“text.txt”,”a”); The fopen() function returns false if the file cannot be opened for any reason. Therefore, its a good idea to test the function’s return value before proceeding to work with it. You can do so with an if statement: If ($fp = fopen(“test.txt”,”w”)) { //do something with the $fp resource } Or, we can use a logical operator to end execution if an essential file can’t be opened: ($fp = fopen(“text.txt”,”w”)) or die(“couldn’t open file. Sorry”); If the fopen() function return true, the rest of the expression won’t be parsed, and the die() function (which writes a message to the browser and ends the script) is never reached. Otherwise, the right side of the or operator is parsed and the die() function is called. Assuming that all is well and we go on to work with your open file, you should remember to close it when you finish. We can do so by calling fclose(), which requires the file resource returned from a successful fopen() call as its argument: Fclose($fp); Opening and Reading a File Line by Line <? $filename=”test.txt”; $fp=fopen($filename,”r”) or die(“couldn’t open $filename”); While (!feof($fp)) { $line=fgets($fp, 1024); Echo “$line<br>”; } ?> Reading a File with fread() <? $filename=”test.txt”; $fp=fopen($filename, “r”) or die(“couldn’t open $filename”); While (!feof($fp)) { $chunk=fread($fp,8); Echo”$chunk<br>”; } ?>

[Type text]

Page 26


Moving around a file with fseek() <? $filename=”test.txt”; $fp=fopen($filename,”r”) or die(“couldn’t open $filename”); $fsize=filesize($filename); $halfway=(int)($fsize/2); Echo “Halfway point: $halfway <br> \n”; Fseek($fp, $halfway); $chunk=fread($fp, ($fsize - $halfway)); Echo $chunk; ?> Reading Characters from a File with fgetc() The fgetc() function is similar to fgets() except that it returns only a single character from a file every time it is called. Because a character is always one byte in size, fgetc() doesn’t require a length argument. Writing to a file with fwrite() or fputs() The fwrite function accepts a file resource and a string, and then writes the string to the file. The fputs() function works in exactly the same way. Fwrite($fp,”hello world”); Fputs($fp,”hello world”); Example:readlines.php <? $filename=”test.txt”; Echo “<p>Write to $filename ..</p>”; $fp = fopen($filename, “w”) or die(“Couldn’t open $filename”); Fwrite($fp,”Hello World \n”); Fclose($fp); Echo “<p>Appending to $filename ..</p>”; $fp=fopen(4filename,”a”) or die(“couldn’t open $filename”); Fputs(4fp, “And another thing \n”); Fclose($fp); ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 27


Working with Directories Creating Directories with mkdir() The mkdir() function enables you to create a directory. The mkdir() function requires a string that represents the path to the directory we want to create. Mkdir(“testdir”,0777); //global read/write/execute permissions Mkdir(“testdir”,0755); // world and group: read/execute only // owner: read/write/execute Removing a Directory with rmdir() The rmdir() function enables you to remove a directory from the file system if the process running your script has the right to do so, and if the directory is empty. rmdir(“testdir2); Opening a directory for reading with opendir() Before you can read the contents of a directory, we must first obtain a directory resource. We can do so with the opendir() function. $dh=opendir(“testdir”); Reading the contents of a Directory with readdir() <? $dirname=”.”; $dh=opendir($dirname) or die(“couldn’t open directory”); While(!((4file =readdir($dh)) === false)) { If (is_dir(“$dirname/$file”)) { Echo “(D) “; } Echo “$file<br>”; } Closedir($dh); ?>

[Type text]

Page 28


Pre Hypertext pre-Processor (PHP) Course Lesson 6 Getting information about the browser Example 1:browser.php <? $browser=$_server[‘http_user_agent’]; Echo “The Sniffer says: $browser”; ?> Pre-defined variables $_server[‘variable’] Here are some other variable names you may find useful. PHP_SELF The path to the current script SERVER_NAME The Server your script is running on HTTP_USER_AGENT The user’s browser and operating system HTTP_REFERER Gives the previous page the visitor is from HTTP_ACCEPT_LANGUAGE The user’s language setting e.g. en_gb Example 2: browser2.php <? $lang=$_server[‘http_accept_language’]; If ($lang==”en_gb”) { Echo “Hello! Would you like a cup of tea?”; } Elseif ($lang==”fr”) { Echo “BonJour! Voulez-vous un croissant?”; } Elseif ($lang==”es-max”) { Echo “Hola! Quieres untaco al pastor?”; } Else { Echo “Hi, not sure where you’re from, but Welcome anyway!”; } ?> Passing information using the URL You have probably noticed web pages with long addresses Like http://www.umicom.com/orflame/index.php?chapter=5&page=85&mode=free The question mark after the filename indicates that there are variables to follow, and each name-value pair is joined by an equal sign So the URL above tells the server Chapter=5 In HTML tag- to create Hypertext Page=85 Mode=free <A HREF=”Preview.php?chapter=5&mode=free”>Preview Chapter Five for free!</a> Getting, information from the query string. $_GET[‘$chapter’] i.e. $chap=$_get[‘$chapter’];

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 29


Example: passurl.php <? $chap=$_get[‘chapter’]; $mode=$_get[‘mode’]; Echo “You are about to preview chapter $chap in $mode mode Hope you enjoy it!”; ?> First (almost) dynamic page Example – colours.php <? $bgcol=$_get[‘bg’]; $txtcol=$_get[‘tx’]; ?> <html> <body bgcolor=”<? Echo $bgcol; ?>” text=”<? Echo $txcol; ?>” > </body> </html> Colours.php?bg=blue&tx=white If we forget to give values to the variables we will get errors, luckily in PHP we can check using array_key_exists() Example <? If (array_key_exists(‘bg’,$_get)) { $bgcol=$_get[‘bg’]; } Else { $bgcol=”#ffffff”; } $txcol=array_key_exists(‘tx’,$_get)?$_get[‘tx’]:”#000000”; ?> <p> Background </p><A HREF=”colours.php?bg=FF0000”>Red</a>~<A HREF=”colours.php?bg=00ff00”>Green</a>~ <A HREF=”colours.php?bg=0000ff”>Blue</a>~<A HREF=”Colours.php?bg=ffffff”>White</a> <p>TEXT:</p><A HREF=”colours.php?tx=ff0000”>Red</A>~<A HREF=”colours.php?tx=00ff00”>Green</A>~ <A HREF=”colours.php?tx=0000ff”>Blue</A>~<A HREF=”colours.php?tx=ffffff”>White</A></body></html>

[Type text]

Page 30


Pre Hypertext pre-Processor (PHP) Course Lesson 7 Server Side Includes (SSI) Example: Scores.php <? $hiscore=”ahmed”; $loscore=”munir”; ?> Example: aboutincludes.php <? Include ‘includes/scores.php’; Echo “Today’s high scorer is $hiscore..”; Echo “...and today’s loser is $loscore!”; ?>

Making header and footer files Imagine we have a site with some common information which is the same across the whole site. Example: header.php <html><head><title><? Echo $page; ?></title></head><body bgcolor=”<? Echo $bg; ?>”>

Example: autumn.php <? $page=”The Autumn Collection”; $bg=”#d08283”; Include ‘includes/header.php’; ?><h2> <? Echo “$sitename: $page”; ?></h2> Our seasonal speciality is the brown hooded top <br/><br/> For more info, email <A HREF=”mailto: <? Echo $email; ?>”> <? Echo $email; ?> </a> <? Include ‘includes/footer.php’; ?> Example: footer.php </body></html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 31


Pre Hypertext pre-Processor (PHP) Course Lesson 8 A simple HTML Example 1: simpleform.html <html> <head> <title>A simple HTML form: by Ahmed Sammy Hegab</title> </head> <body> <form action=”send_simpleform.php” method=”post”> <p><strong>Name:</strong><br> <input type=”text” name=”user”></p> <p><strong>Message:</strong><br> <textarea name=”message” rows=”5” cols=”40”></textarea></p> <p><input type=”submit” value=”send”></p> </form> </body> </html> Example 2: send_simpleform.php <? Echo “<p>Welcome <b>$_post[user]</b></p>”; Echo “<p>Your message is:<br><b>$_post[‘message]</b></p>”; ?> Creating a simple Feedback form Example 3: feedback.html <html> <head> <title> E-mail form</title> </head> <body> <form action=”sendmail.php” method=”post”> <p><strong>Name:</strong><br><input type=”test” size=”25” name=”name”></p> <p><strong>E-mail Address:</strong><br><input type=”test” size=”25” name=”email”></p> <p><strong>Message:</strong><br> <textarea name=”message” cols=30 rows=5></textarea></p> <p><input type=”submit” value=”send”></p> </form> </body> </html>

[Type text]

Page 32


Example 4: sendmail.php <html> <head> <title>Sending mail from the form</title> </head> <body> <? Echo “<p>Thank you, <b>$_post[name]</b>, for your message1</p>”; Echo”<p>Your email address is : <b>$_post[email]</b>.</p>”; Echo “<p>Your message was:<br>”; Echo “$_post[message]</p>”; // Start building the mail string $msg =”Name: $_post[name] \n”; $msg .=”E-mail: $_post[email] \n”; $msg .=”Message: $_post[message] \n”; // setup the mail $recipient = “admin@umicom.com”; $subject = “Form submission results”; $mailheaders=”From: My Web site Sammy@umicom.com \n”; $mailheaders .=”Reply-To: $_post[email]”; // send the mail Mail (“recipient, $subject, $msg, $mailheaders); ?> </body> </html>

Working with File Uploads A Simple File Upload Form Example: fileupload.html <html> <head> <title>A simple file upload form</title> </head> <body> <form action=”do_upload.php” enctype=”multipart/form-data” method=”post2> <input type=”hidden” name=”MAX_file_size” value=”51200”> <p><strong>File to Upload:</strong><input type=”file” name=”fileupload”></p> <p><input type=”submit” value=”upload!”></p> </form> </body> </html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 33


Example: do_upload.php <? $file_dir=”/path/to/upload/directory”; Foreach($_files as $file_name=> $file_array) { Echo “path: “.$file_array[‘tmp_name’].”<br>\n”; Echo “name: “.$file_array[‘name’].”<br>\n”; Echo “type: “.$file_array[‘type’].”<br>\n”; Echo “size: “.$file_array[‘size’].”,br>\n”; If (is_uploaded_file($file_array[‘tmp_name’])) { Move_uploaded_file($file_array[‘tmp_name’])) { Move_uploaded_file($file_array[‘tmp_name’], “$file_dir/$file_array[name]”) or die (“Couldn’t copy”); Echo “file was moved!<br><br>”;}}?> Handling forms There are two display pages associated with handling any form First, there must be a page which sets up the form so that the user can enter data into it, then there is a page which displayed after the form has been sent and the data processed in the same way. These two functions may be performed by separate scripts, but they are often handled by a single script which uses a control structure to determine whether to display the form or process it. The benefits of this become clear when we start validating the data: with two scripts, if the user enters some bad data, all we can really do is display an error message and send the user back to the form page. With a single script, you can redisplay the form with any bad data clearly flagged up for the user’s attention. Setting up the form Creating the form does not have to involve any PHP at all – it can simply be a plain HTML form, with the form’s ACTION attribute get to the PHP script which will process the form. Example: formsender.php <form method=”post” action=”formhandler.php”> <p> Your message:<input type=”text” name=”msg” /> <p> Your favourite colour: <select name=”col”> <option value=”#ff0000”>Red</option> <option value=”#00ff00”>Green</option> <option value=”#0000ff”>Blue</option> </select> <p><input type=”submit” value=”send” /> </form>

[Type text]

Page 34


Example: formhandler.php <html> <body bgcolor=”<? Echo $_post[‘col’] ?>”> <? Echo $_post[‘msg’] ?> <p><A HREF=”formsender.php”>Let’s go again!</A> </body> </html> Your first fully interactive page Instead of using separate scripts to send and receive the form data, lets combine them into one script. When using a single script to both send and receive form data, the ACTION will point to itself instead of a second file – perhaps using $_SERVER[‘PHP_SELF’] <FORM METHOD=”POST” ACTION=”<? Echo $_server[‘PHP_SELF’] ?>” > We can’t have the page referring to the posted data until after we are sure that the form has been sent, so we need to build a control structure around the form and the echoed message. The syntax for asking whether a variable exists in simply If ($_post) The two separate pages we did before can be combined into are like this. Example: <html> <? If ($_post) { ?> <body bgcolor=”<? Echo $_post[‘col’] ?>” > <? Eco $_post[‘msg’] ?> <p> <a href=”<? Echo $_server[‘pho_self’] ?>” > Let’s go again! </a> <? } Else { ?> <body> <form method=”post” action=”<? Echo $_server[‘php_self’] ?>” > <p>Your message: <input type=”text” name=”msh” size=”45” /> <p> Your favourite colour: <select name=”col”> <option value=”#ff0000”>Red</option> <option value=”#00ff00”>Green</option> <option value=”#0000ff”>Blue</option> </select><p><input type=”submit” value=”send” /> </form> <? } ?> </body></html>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 35


Cleaning and Validating data Before we can be sure that the information sent to us by a form is really useful we need to know two things: 1) Is the data ‘clean’ – is it in the format we want it? Or does it have rogue characters in it like leading spaces 2) Is the data valid? Do we have data for all the required fields? Cleaning and validating data is an important part of form handling, and to do it we need some advanced string functions Strlen ($str) – Returns the number of characters in the string Trim($str) – Removes spaces from both ends of string Strtolower($str) – Converts all characters in $str to lower case. nL2br($str) – Replaces any new lines in $str with HTML <br/> tags ( useful for displaying long pieces of text from a TEXTAREA input) strpos($str,$x) searches $str and returns the first occurrence of $x as a number If $x is not found in $str, the function returns FALSE case-sensitive. Stripos($str,$x) same as above but (not) case sensitive Is_numeric($str) Returns True if $str can be handled as a number Ctype_alpha($str) returns TRUE if $str contains only alphabetic characters.

A good starting point is to take the $_post array and turn it into a set of separate variables. This gives us nice neat variable names we can do this by running a Foreach-loop through the array, and assigning the form;s name-value pairs to named variables (using the field names as variable-variables) Foreach ($_post as $fn=>$v) { $$fn =$v; } Trim white space Example Foreach ($_post as $fn=> $v) { $v=trim($v); $$fn=$v; }

[Type text]

Page 36


Validation The first piece of validation we need to do is to make sure that no required fields were left blank. $error=” “; If (($name==” “) || ($email==” “) || ($telephone==” “)) { $error=”Please fill in all the required fields <br/>”; } If (is_numeric($telephone)==false) { $error=”Please enter a valid telephone (numbers only!)”; } If((strpos($email,”@”)===false) || (strops($email,”.”)===false) { $error =”Please enter a valid email address”; } The final check is to see whether there is a dot after the @ We will do this by comparing the position of the @ with the position of the last dot (strops($email, “@”) > strops($email,”.”)) So the complete conditions looks like this If ((strpos($email,”@”)==FALSE) ||(strpos($email,”.”)==FALSE)||(strpos($email, “ “) !=FALSE) || (strpos($email,”@”) >strops($email,”.”))) { $error=”please enter a valid email address”; } Example <html><head><link ref=”stylesheet” type=”text/css” href=”plain.css” /></head> <body> <? If ($_post) { Foreach($_post as $k=>$v) { $v=trim($v); $$k=$v; } // create empty error variable $error =””; //check for data in required fields If (($forename==” “) || ($surname==” “) || ($email==” “)) { $error=”Please fill in all the required fields <br/>”; } // Validate $age If (is_numeric($age)==false) { $error=”Please enter a valid age (numbers only!) <br/>”; } // Validate $email If ((strops($email,”@”)==false) || (strops($email,”.”)==false) || (strops($email,” “) !=false) || (strops($email,@”)>strops($email,”.”))) { $error=”Please enter a valid email address <br/>”; } // Clean and validate $ $notel=array(“+”,” “,”(“,”)”,”[“,”]”,”-“,”,”,”#”); $tel=str_replace($notel, array(00”),$tel); If(is_numeric($tel)==false) { $error=”Please enter a valid telephone number <br/>”; } // Clean blog and add <br/> $bios=stripslashes($blog); If($error !=” “) { echo “$error <p> Please hit the back button to try again.”; } else { Echo “<p> <b> Forename: </b> $forename <br/>”; Echo “<b>Surname: </b> $surname<br/>”; Echo “<b>Age:</b>$age<br/>”; Echo “<b>sex:</b>$sex<br/>”; Echo ”<b>email:</b>$email<br/>”; Echo “<b>Telephone:</b>$tel<br/>”; Echo “<b>Description:</b>$blog<br/>”; } else { ?><table border=”0” cellpadding=”3£ cellspacing=”0”> <form method=”post” action=”<? Echo $_server[‘PHP_SELF’] ?>”> <tr><td>Forename: </td> <td><input type=”text” name=”forename” size=”45” maxlength=”100” /></td> </tr><tr><td>Age: </td><td><input type=”text” name=”age” size=”5” maxlength=”5” /></td>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 37


</td><tr><td>sex:</td><td><input type=”radio” name=”sex” value=”f” /> F     <input type=”radio” name=”sex” value=”M” /> M</TD> </tr><tr> <td>Email:</td> <td><input type=”text” name=”email” size=”45” maxlength=”100! /> </td></tr><tr> <td> Telephone: </td> <td><input type=”text” name=”tel” size=”45” maxlength=”20” /> </td></tr><tr><td colspan=”2”> Describe yourself in a few words: </td> </tr><tr><td colspan=”2”><textarea name=”blog” rows=”4” cols=”47”></textarea></td> </tr><tr><td colspan=”2”><input type=”submit” value=”send” /></td> </tr></form></table> <? } ?></body></html>

Displaying helpful error messages Ideally, a form with invalid data should be redisplated, with the problem fields clearly flagged, and all submitted data dropped into the right places. Displaying data in the form <input type=”test” name=”age” value=”<? Echo $age; ?>” />

To handle radio buttons we would need to add some variables to the form code: <input type=”radio” name=”sex” value=”f” <? Echo $sexf_sel; ?> /> <input type=”radio” name=”sex” value=”m” <? Echo $sexm_sel; ?> /> $sexf_sel=$sexm_sel=” “; If ($sex==”f”) { $sexm_sel=”checked”; } elseif ($sex==”m”){ $sexf_sel=”checked”; } Highlight error messages <style type=”text/css”> .error { border:1px solid #fff0000; Background_color: #ddddff; } </style> <? //create default (empty) variables $forename_x=$surname_x=$age_x=$email_x=$tel_x=” “; //test for error conditions If ($forename==” “) { $forename_x=”error”; } Etc... <tr> <td> Forename: </td> <td><input type=”text” name=”forename” value=”<? Echo $forename; ?>” class=”<? Echo $forename_x; ?>” /> </td></tr> Etc... Reset button <input type=”button” value=”clear fields” onClick=”location.href=’<? Echo $_server[‘php_self’]?>’; “ />

[Type text]

Page 38


Pre Hypertext pre-Processor (PHP) Course Lesson 9 Sessions and Cookies We will learn about: 1. Browser sessions 2. How to store and use session variables 3. About cookies 4. How to store and use cookies 5. How to set HTTP headers Session variables and cookies When web page information is transmitted between a web server and a browser, it is sent via a protocol called Hypertext Transfer protocol- HTTP This protocol is said to be ‘stateless’ – which basically means that a web server has no long-term memory This is inconvenient for web developers who frequently want to retain information about a user as they hop around their site, or even between visits. Information stores in a session variable exists for a limited period, generally until the user closes their browser. Cookies may still be retrieveable at a later session – days, weeks, or even years later. However, cookies can be refused by users, whereas sesson variables can to an extent circumvent this restriction. Start sessions often and early! Session_start() must be called on any page where you want to make use of session variables Example: firstpage.php <? Session_start(); $username=”lancelot”; $_session[‘user’]=$username; ?>

Example: secondpage.php <? Session_start(); $stored_username=$_session[‘user’]; ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 39


Pre Hypertext pre-Processor (PHP) Course Lesson 10 Using PHP with MYSQL We will learn the following • How to use PHP to connect to a MySQL database. • How to use PHP to extract and display data from a database. • How to use PHP to add new records or work with existing ones. Opening and closing connections Before a web page can talk to a database and swap information with it, we need to open a connection between them. To do this you need four pieces of information. -

The host name of the database server A username A password The name of the database you want to work with.

To open connection $link=mysql_connect(‘supremeserver22’,’umicom_home’,’test’); This opens the connection and assigns to the varable $link To close connection Mysql_close($link); Extracting records from the database $select=”SELECT first_name, last_name from customers where id=1”; The next step is to execute he query and assign the result to a variable. $result=mysql_query($link,$select); Displaying a single record // assign the results to an array $row=mysql_fetch_array($result); //get each array element and give it // a variable name of its own $fn=$row[‘first_name’]; $ln=$row[‘last_name’]; // print the results Each <<<EOF <2> Query results: </h2> First name: $fn<br/> Last name: $ln<br/> EOF; Display Multiple Records Instead of pulling out a specific record, suppose over query is designed to extract certain pieces of information from every record.

[Type text]

Page 40


$select=”SELECT first_name, last_name FROM customers”; We can then loop through the result object, putting each record into a fresh array, pulling the values out of it and displaying them. // As long as there is a record, keep looping. While ($row=mysql_fetch_array($result)) { // get each element and put it in a variable $fn=$row[‘first_name’]; $ln=$row[‘last_name’]; // Print them out Eacho “Name: $fn $ln <br/> <br/>”; //Loop back to the next record } Displaying records in a table <!—Setup the table <table border=”1” cellpadding=”5”> <tr> <th>First name </th> <th>Last Name</th> <th>Telephone</th> <th>Email address</th> </tr> <? //build and execute the query $select=”SELECT first_name, last_name, tel, email from customers”; $result=mysql_query($link, $select); //loop through the results While($row=mysql_fetch_array(4result)) { //get each element and put it in a variable $fn=$row[‘first_name’]; $ln=$row[‘last_name’]; //print out the code for each row Each <<<END <tr><td>$fn</td><td>$ln</td><td>$tel</td><td>$email</td> </tr> end; } ?></table>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 41


Sorting Records $select=”SELECT first_name, last_name, tel, email from customers order by Last_name”; $select=”SELECT first_name, last_name, tel, email from customers ORDER by last_name, first_name”; Filtering records Using the SQL where clause is by far the best way to narrow down a database search Highlighting records For instance, we might want to highlight certain customers according to the status we have given them. To do this we will need to supply some CSS styles, and a conditional expression inside the loop which fetches and displays the query results. <style> .normal {background-color:#ffffff; color:#000000; } .green {background-color:#00ff00; color:#000000; } .red {background-color: #ff0000; color:#ffffff; } </style> <? While ($row=mysql_fetch_array($result)) { $fn=$row[‘first_name’]; $ln=$row[‘last_name’]; $tel=$row[‘tel’]; $email=$row[‘email’]; $status=$row[‘status’]; // determine row class by status If($status==2) { $row_class=”green”; } Elseif ($status==3) { $row_class=”red”; } Else { $row_class=”normal”;} Echo <<< END <tr class=”$row_class”> <td>$fn</td> <td>$ln</td> <td>$tel</td> <td>$email</td> </tr> End; } ?> Putting data into the database The main thing to note is that when an Insert or update query is executed, there is no result object to be retured instead, PHP returns True or False. We can use this to pass an appropriate message to the user:

[Type text]

Page 42


$insert=”INSERT into customers (first_name, last_name) Values (‘$fn’,’$ln’)”; //execute query and check for success If (!mysql_query($link, $insert)) { $msg=”Error inserting data”; } Else { $msg=”record successfully added”; } Adding new customer <h2> Add new customer </h2> <style> .error { padding:10px; color:#cc0000; font_weight:bold; } </style> <? // Has form been submitted If ($_post) { //create empty error variable $msg=” “; //put form data into variable variables Foreach($_post as $k=>$v) { $v=trim($v); $$k=$v; //check for data in both fields If ($v=” “) { $msg=”Please fill in both fields”; } } // If all data is there, build query If($msg==” “) { $insert=”Insert into customers (first_name,last_name) Values(‘$fn’,’$ln’)”; //Open db connection Include ‘includes/db_conn.txt’; //execute query and check for success If(!mysql_query($link,$insert)) { $msg=”Error inserting data”; } Else { $msg=”Record successfully added”; //set vars to “ “ for next form input $fn=$ln=” “; } Mysqli_close($link); }

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 43


// Print error or success messages Echo “<div class=\”error\”>$msg</div>”; //If not submitted, create blank vars for form inputs } Else { $fn=$ln=” “; } ?> <form method=”post” Action=”<? Echo $_server[‘PHP_SELF’] ?>”> <Table border=”1” cellpadding=”5”> <tr> <th> First name</th> <th>Last name</th> </tr> <tr> <td><input type=”text” Name=”fn” value=”<? Echo $fn ?>” /></td><td><input type=”text” name=”ln” value”<? Echo $ln ?>” /></td> </tr> </table> <br/> <input type=”submit” value=”Add to database” /> <input type=”reset” value=”Cancel” /> </form> Updating an existing record Our first task is to specify and locate the record to be updated. While ($row=mysql_fetch_array($result)) { $fn=$row[‘first_name’]; $ln=$row[‘last_name’]; $id=$row[‘id’]; Echo <<<END <tr><td>$fn</td> <td>$ln</td> <td><a href=”editcust.php?id=$id”>Edit details</a></td></td></tr> End;

Example: editcust.php <html> <head> <style> Body { font-family:arial; } .error {font-weight:bold; color:#ff0000; } </style> </head> <body> <h2> Edit customer details:</h2> <? //connect to the database Include ‘includes/db_conn.txt’; //Has the form been submitted? If($_post) { Foreach ($_post as $k=>$v){ $v=trim ($v); $$k=$v;

[Type text]

Page 44


} //build update query $update=”update customers set first_name=’$fn’, last_name=’$ln’, tel=’$tel’, email=’$email’ where ID=$id”; //execute query and check for success If(!mysql_query($link,$update)){ $msg=”Error updating data”; } else { $msg=”Record successfully updated:”; // Write table row confirming data $table_row=<<<EOR <tr> <td>$fn</td> <td>$ln</td> <td>$tel</td> <td>$email</td> </tr> Eor; } // If not posted, check that an ID has been // passed via the URL } else { If(!IsSet($_get[‘id’])) { $msg=”No customer selected!”; } else { $id=$_get[‘id’]; //build and execute the query $select=”SELECT first_name, last_name, tel, email from customers where ID=$id”; $result=mysql_query($link,$select); //check that the record exists If(mysql_num_rows($result)<1){ $msg=”No customer with the ID found!”; } Else { //set vars for form code $form_start=”<form method=\”post\” action=\” “.$_server[‘php_self’],”\”>”; $form_end=<<<EOF <tr> <td colspan=”2”><input type=”submit” value=”submit changes” /></td> <td colspan=”2”><input type=”reset” value=”cancel” /></td> </tr> </form> Eof;

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 45


// assign the results to an array While ($row=mysql_fetch_array($result)) { $fn=$row[‘first_name’]; $ln=$row[‘last_name’]; $tel=$row[‘tel’]; $email=$row[‘email’]; // Write table row with form fields $table_row=<<EOR <tr><td><input type=”text” name=”fn” value=”$fn” size=”10” /> </td> <td><input type=”text” name=”ln” value=”$ln” size=”10” /></td> <td><input type=”text” name=”tel” value=”$tel” size=”12” /></td> <td><input type=”text” name=”email” value=”$email” size=”15” /></td></tr> Eor; } //end ‘if record exists’ if } //end ‘if ID given in URL’ if } //end if form posted’ if } // close connection Mysql_close($link); //print error/success message Echo (IsSet($msg))?”<div class=\”error\”>$msg</div>”:” ”; ?> <table border=”1” cellpadding=”5”> <!—show start of form code if form needed <? Echo(IsSet($form_start))?$form_start:” “; ?> <input type=”hidden” name=”id” value=”<? Echo $id ?>” /> <tr> <th>First name</th> <th>Last name</th> <th>Tel</th> <th>Email</th> </tr> <!—Show appropriate table row code (none set if there were errors) <? Echo (IsSet ($table_row))?$table_row:” “; ?> <!—Show end-of-form code if we are displaying the form <? Echo (IsSet($form_end))?$form_end:” “; ?> </table> <br/><a href=”custlist.php”>Back to customer list</a> </body> </html>

[Type text]

Page 46


Creating Multidimensional Arrays The first two types of arrays hold strings and integers, whereas this third type holds other arrays. If each set a key/value pairs consititutes a dimension, a multi-dimensional array holds more than one series of these key/value paris. For example below defines a multidimensional array called $characters, each element of which contacins an associative array Example: mutlidimensionaArray.php <? $characters=array( Array( “name”=>”Bob”, “occupation”=>”superhero”, “age”=>30, “special power”=>”x-ray vision” ), Array( “name”=>”Sally”, “occupation”=>”superhero”, “age”=>24, “special power”=>”superhuman strength” ), Array( “name”=>”Jane”, “occupation”=>”arch villain”, “age”=>45, “special power”=>”nanotechnology” ) ); ?> // to reference this array we need to refer to the second array $characters[1][‘occupation’]; <? Echo $characters[1][‘occupation’]; ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 47


Some array-related functions Approximately 60 array-related functions are bult into PHP, which you can read about in detail at http://www.php.net/array Some of the more common functions are explained in this section. •

Count() and sizeof() – each counts the number of elements in an array. i.e $color=array(“blue”,”black”,”red”,”green”); Both count($colors); and sizeof($colors); return a value of 4

Each() and list() – These usually appear together, in the context of stepping through an array and returning its keys and values. You saw an example of this above, where we stepped through the $c array and printed its contents. Foreach()—This is also used to step through an array, assigning the value of an element to a given variable, as you saw in the previous section. Reset() – This rewinds the pointer to the beginning an array, as in this example: reset($character); This function is useful when you are performing multiple manipulations on an array, such as sorting, extracting values, and so forth.

• •

Array_push() – This add one or more elements to the end an an existing array, as in this example: Array_push($existingArray,”element 1”,”element 2”,”element 3”);

Array_pop() – This removes (and returns) the last element of an existing array, as in this example: $last_element = array_pop($existingArray);

Array_unshift() – This adds one or more elemets to the beginning of an existing array, as in this example: Array_unshift($existingArray, “element 1”, “element 2”, “element 3”);

Array_shift() – This removes (and returns) the first element of an existing array, as in this example, where the value of the element in the first position of $existingArray is assigned to the variable $first_element: $first_element= array_shift($existingArray);

Array_merge() – This combines two or more existing arrays, as in this example: $newArray=array_merge($array1, $array2);

Array_keys() – This returns an array containing all the key names within a given array, as in this example: $keysArray=array_keys($existingArray);

Array_values() – This returns an array containing all the values within a given array, as in this example: $valuesArray=array_values($existingArray);

Shuffle() – This randomises the elements of a given array. The Syntax of this function is simple as follows: Shuffle($existingArray);

[Type text]

Page 48


Creating an Object Explaining the concept of an object is a little difficult: It’s a sort of theoretical box of things – variables, functions, and so forth – that exists in a template structure called a class. Although it’s easy to visualise a scalar variable, such as $color, with a value of red, or an array called $character with three or four different elements inside it, some people have difficult time visualising objects. To supplement our knowledge in classes and object we need to read up in the php manual found online http://www.php.net/manual/en/language.oop.php The section opened with saying that an object has a structure called a class. In each class, you define a set of characteristics. For example, say that you have created an automobile class. In the automobile class, you might have color, make, and model characteristics. Each automobile object uses all the characteristics, but they are initialised to different values, such as silver, Mazda, and Protege5, or red, Porsche, and Boxter. The whole purpose of using objects is to create reusable code. Because classes are so tightly structured but self-contained and independent of one another, they can be reused from one application to another. For example, suppose you write a text formatting class used in one project and decide you can use that class in another project. Because the class is just a set of characteristics, you can pickup the code and used in the second project, reaching into it with methods specific to the second application but using the inner workings of the existing code to achieve new results. Creating an object is quite simple, as you simply declare it to be in existence: Class myClass { //code will go here } Now that we have a class, we can create a new instance of an object: $object1= new myClass(); Example: proofofclass.php <? Class myClass { // code will go here } $object1 = new myclass(); Echo “\$object1 is an “.gettype($object1); ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 49


Properties of Objects The variables declared inside an object are called properties. It is standard practice to declare your variables at the top of the class. These properties can be values, arrays, or even other objects. The following snippet uses simple scalar variables inside the class, prefaced with the var keyword: <? Class myCar { Var $color=”silver”; Var $make=”Mazda”; Var $model=”Protege5”; } $car= new myCar(); Echo “I drive a “.$car->color.” “.$car->make.” “.$car->model; ?> Example: objproperties2.php <? Class myCar { Var $color; Var $make; Var $model; } $car=new myCar(); $car-> color=”red”; $car->make=”Porsche”; $car->model=”Boxter”; Echo “I drive a “.$car->color.” “.$car->make.” “.$car->model; ?> Object Methods Methods add functionality to your objects. No longer will they be sitting there, just holding on to their properties for dear life— they’ll actually do something! Example: helloclass.php <? Class myClass { Function sayhello() { Echo “Hello!”; } } $object1= new myClass(); $object1->sayhello(); ?> So, a method looks and acts like a normal function but is defined within the framework of a class. The-> operator is used to call he object method in the context of your script. Had there been any variables stored in the object, the method would have been capable of accessing them for its own purposes. <? Class myClass { Var $name=”Ahmed”; Function sayHello() {

[Type text]

Page 50


Echo “Hello! My name is “.$this->name; }} $object1=new myClass(); $object1->sayHello(); ?> The special variable $this is used to refer to the currently instantiated object. Anytime an object refers to itself, you must use the $this variable. Using the $this variable in conjunction with the -> operator enables you to access any property or method in a class, within the class itself. Changing the value of a property from within a method <? Class myClass { Var $name=”Jumbo”; Function setName($n) { $this->name=$n; } Function sayhello() { Echo “Hello! My name is “.$this->name; }} $object1 = new myClass(); $object1 ->setName(“Julie”); $object1->sayHello(); ?> Constructors A constructor is a function that lives within a class and, given the same name as the class, is automatically called when a new instance of the class is created using new classname. Using constructors enables you to provide arguments to your class, which will then be processed immediately when the class is called. You see a constructors in action in the next section, on object inheritance. Object Inheritance Having learned the absolute basics of objects, properties, and methods, you can start to look at object inhertitance. Inheritance with regard to classes is just what it sounds like: One class inherits the functionality from its parents class. A class inheriting from its parents Example: inheritance.php <? Class myClass { Var $name=”Matt”; Function myClass ($n) { $this ->name=$n; } Function sayHello() { Echo “Hello” My name is “.$this->name;} } Class childClass extends myClass { //code goes here } $object1=new childClass (“Baby Matt”); $object ->sayHello(); ?>

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 51


Pre Hypertext pre-Processor (PHP) Course Lesson 11 Working with Images Drawing a New Image The basic PHP function used to create a new image is called ImageCreate(), bu creating an image is not as simple as just calling the function. Creating an image is a stepwise process and includes the use of several different PHP functions. Creating an image begins with the ImageCreate() function, but all this function does is set aside a canvas area for your new image. The following line creates a drawing area that is 150 pixel wise by 150 pixels high: $myimage=ImageCreate(150,150); With a canvas now defined, you should next define a few colors for use in that new image. ImageColorAllocate() function and RGB values: $black=ImageColorAllocate($myImage, 0,0,0); Drawing shapes and Lines • ImageEllipse() is used to draw an ellipse. • ImageArc() is used to draw a partial ellipse. • ImagePolygon() is used to draw a polygon • ImageRectangle() is used to draw a rectangle i.e. ImageRectangle($myImage, 15,15,40,55, $red); • ImageLine() is used to draw a line. Example: imagecreate.php <? //create the canvas $myImage=ImageCreate(150,150); //set up some colors $black=ImageColorAllocate($myImage,0,0,0); $white=ImageColorAllocate($myImage,255,255,255); $red = ImageColorAllocate($myImage, 255, 0,0); $green=ImageColorAllocate($myImage,0,255,0); $blue=ImageColorAllocate($myImage,0,0,255); //draw some rectangles ImageRectangle($myImage, 15,15, 40,55,$red); ImageRectangle($myImage, 40, 55, 65, 95,$white); //output the image to the browser Head(“content-type: image/png”); ImagePng($myImage); // clean up after yourself ImageDestroy($myImage); ?>

[Type text]

Page 52


Using a color fill PHP has image functions designed to fill areas as well: • ImageFilledEllipse() is used to fill an ellipse • ImageFilledArc() is used to fill a partial ellipse • ImageFilledPolygon() is used to fill a polygone • ImageFilledRectangle() is used to fill a rectangle. Creating a New Image with Color Fills Example: imagecreatefill.php <? //Create the canvas $myImage=ImageCreate(150,150); //set up some colors $black=ImageColorAllocate($myImage,0,0,0); $white=ImageColorAllocate($myImage,255,255,255); $red = ImageColorAllocate($myImage, 255, 0,0); $green=ImageColorAllocate($myImage,0,255,0); $blue=ImageColorAllocate($myImage,0,0,255); //draw some rectangles ImageFilledRectangle($myImage, 15,15, 40,55,$red); ImageFilledRectangle($myImage, 40, 55, 65, 95,$white); //output the image to the browser Head(“content-type: image/png”); ImagePng($myImage); // clean up after yourself ImageDestroy($myImage);?> Getting Fancy with Pie Charts A basic pie chart Example: <? //create the canvas $myImage = ImageCreate(150,150); //set up some colors $white=ImageColorAllocate($myImage, 255, 255,255); $red = ImageColorAllocate($myImage, 255, 0,0); $green=ImageColorAllocate($myImage,0,255,0); $blue=ImageColorAllocate($myImage,0,0,255); // draw a pie ImageFilledArc($myImage, 50, 50, 100, 50,0,90,$red, IMG_arc_pie); ImageFilledArc($myImage, 50, 50, 100, 50, 91,180,$green, img_arc_pie); ImageFilledArc($myImage, 50,50,100,50,181, 360, $blue, img_arc_pie); //output the image to the browser Header(“Content-type:image/png”); ImagePng($myImage); //clean up after yourself ImageDestroy($myImage); ?> The Imagefilledarc says to begin the arc at point 50,50 and give it a width of 100 and height of 50. The start point is 181, and the end is 360. More information on images available in the PHP manual on http://www.php.net/image

[ Learning PHP | Video Tutorials available on www.umicity.com ]

Page 53


Modifying Existing Images The process of creating images from other images follows the same essential steps as creating a new image – the difference lies in what acts as the image canvas. When we creating an image from a new image, you use the ImageCreateFrom() family of functions. We can create images from existing Gifs, jpgs, pngs an plenty of other image types

[Type text]

Page 54


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.