Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

Similar presentations


Presentation on theme: "PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |"— Presentation transcript:

1 PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |

2 Today’s Topics Introduction Fundamentals of PHP Using Variables Selection Statements Repetition Statements Lecture 6: Programming in PHP | SCK3633 Web Programming |

3 Introduction PHP (PHP Hypertext Preprocessor) is a web scripting language. Specifically designed for web-based application development. It is a server-pages technology. PHP script is embedded into HTML. Lecture 6: Programming in PHP | SCK3633 Web Programming |

4 What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP is a server-side scripting language, like ASP PHP scripts are executed on the server even though even though combined with an HTML code PHP scripts are executed on the server even though even though combined with an HTML code PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is an open source software (OSS) PHP is free to download and use PHP is free to download and use Lecture 6: Programming in PHP | SCK3633 Web Programming |

5 What is a PHP File? PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml" Lecture 6: Programming in PHP | SCK3633 Web Programming |

6 Web-based Architecture Using PHP Lecture 6: Programming in PHP | SCK3633 Web Programming |

7 How PHP Pages are Accessed and Interpreted Lecture 6: Programming in PHP | SCK3633 Web Programming |

8 Where to Start? Install an Apache server on a Windows or Linux machine Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine Install PHP triad All in one LAMP –Linux Apache MySQL PHP Lecture 6: Programming in PHP | SCK3633 Web Programming |

9 XAMPP for Windows Download xampp-win32-1.7.4-VC6- installer.exe from http://sourceforge.net Download xampp-win32-1.7.4-VC6- installer.exe from http://sourceforge.nethttp://sourceforge.net Double-click the.exe file you downloaded. Double-click the.exe file you downloaded. Choose a language from the menu, and then click OK Choose a language from the menu, and then click OK * In Vista you may see a message warning you that XAMPP may not work when installed in the C:\Program Files directory. Install in C:\XAMPP or D:\XAMPP Lecture 6: Programming in PHP | SCK3633 Web Programming |

10 Click Install and finally, click the Finish button. Click Install and finally, click the Finish button. Click Yes, to open the XAMPP Control Panel Click Yes, to open the XAMPP Control Panel Lecture 6: Programming in PHP | SCK3633 Web Programming |

11 Start Apache and MySQL by clicking on the "Start" buttons next to each item. If prompted by Windows Firewall, click the button labelled "Unblock" Start Apache and MySQL by clicking on the "Start" buttons next to each item. If prompted by Windows Firewall, click the button labelled "Unblock" Lecture 6: Programming in PHP | SCK3633 Web Programming |

12 Open web browser. Go to http://localhost/. If you are directed to a page with the XAMPP logo, your installation is successful. http://localhost/ Lecture 6: Programming in PHP | SCK3633 Web Programming |

13 Example 01 Add files in D:\xampp\htdocs to run PHP scripts at http://localhost/ on any local web browser. Add files in D:\xampp\htdocs to run PHP scripts at http://localhost/ on any local web browser.http://localhost/ Create a new folder tutorial in D:\xampp\htdocs. Create a new folder tutorial in D:\xampp\htdocs. Write a test.php file and copy it in to D:\xampp\htdocs\tutorial Write a test.php file and copy it in to D:\xampp\htdocs\tutorial To run the php file, browse https://localhost/tutorial/test.php To run the php file, browse https://localhost/tutorial/test.php https://localhost/tutorial/test.php Lecture 6: Programming in PHP | SCK3633 Web Programming |

14 Would Output The Following... Lecture 6: Programming in PHP | SCK3633 Web Programming |

15 Embedding PHP into HTML There are different ways to embed PHP scripts into HTML echo "Hello World"; (this format needs the PHP.ini option asp_tag to be turn on) Lecture 6: Programming in PHP | SCK3633 Web Programming |

16 Switching between HTML and PHP can be done at any time. Example: print tag 100 times. Lecture 6: Programming in PHP | SCK3633 Web Programming |

17 Including Files Example: File: hello.php Output in the Web Browser: Hello World Lecture 6: Programming in PHP | SCK3633 Web Programming |

18 Proper Syntax If you have a syntax error then you have written one or more PHP statements that are grammatically incorrect in the PHP language. If you have a syntax error then you have written one or more PHP statements that are grammatically incorrect in the PHP language. The print statement syntax: Lecture 6: Programming in PHP | SCK3633 Web Programming |

19 Improper Syntax Suppose you use the wrong syntax: 1. Lecture 6: Programming in PHP | SCK3633 Web Programming |

20 Syntax Identifiers Variable names are case-sensitive. Function names (both built-in and user-defined functions) are NOT case-sensitive.Comments /* C style comments */ // C++ style comments # Bourne shell style comments PHP Statements are terminated by semicolon. Lecture 6: Programming in PHP | SCK3633 Web Programming |

21 Variables Preceded by a dollar sign ($). There is no limit on the length of a variable name. Variable names in PHP are case-sensitive. Valid Variable Names: $counter$_COUNTER$user_name$user100 Invalid Variable Names: $1counter$#counter Example: Lecture 6: Programming in PHP | SCK3633 Web Programming |

22 Assigning New Values to Variables You can assign new values to variables: You can assign new values to variables: $days = 3; $newdays = 100; $days = $newdays; At the end of these three lines, $days and At the end of these three lines, $days and $newdays both have values of 100. Lecture 6: Programming in PHP | SCK3633 Web Programming |

23 Variables …… In PHP, we do not have to declare variables. Variables are automatically declared by the PHP intepreter, the first time a value is assigned to them. PHP variables are untyped; you can assign a value of any type to a variable. Output ? $var = “Hello World”; echo “$var\n”; $var = 1001; echo ‘ ’ echo “The number is $var\n”; Example: Lecture 6: Programming in PHP | SCK3633 Web Programming |

24 Variables …… In PHP, uninitialized variables have the value undef, which evaluates to different values, depending on its context. undef value for a numeric context is 0 undef value for a string context is an empty string (“”) Output ? $a=100;$str="World"; $msg= $hello. $str; $c = $a + $b; echo $msg, "\n"; echo $c; Example: Lecture 6: Programming in PHP | SCK3633 Web Programming |

25 Dynamic Variables Also known as variable variables. Syntax: $$var or ${$var} Meaning: obtain the value of the variable whose name is equal to the value of $var. Lecture 6: Programming in PHP | SCK3633 Web Programming |

26 Dynamic Variables ….. Output ? $msg = "Hello World"; $var = “msg"; echo $$var; Example 1: How does it work? $$var => $”msg” or $msg => “Hello World”; Lecture 6: Programming in PHP | SCK3633 Web Programming |

27 Dynamic Variables ….. $var ="hello"; $$var = "World"; print $hello; Output ? Example 2: How does it work? We created the variable $hello indirectly, where $$var means $”hello”, or just $hello. The assignment statement $$var=“World” is equal to $hello=“World” Lecture 6: Programming in PHP | SCK3633 Web Programming |

28 Constants Constant is a value that cannot be modified once it is declared. Constants are created using function define. Constant names by default are case-sensitive. Output ? define ("HELLO",“Hi World"); define ("NUMBER", 5); echo HELLO, "\n"; echo ‘ ’ echo "The number is ", NUMBER; Example: Lecture 6: Programming in PHP | SCK3633 Web Programming |

29 Data Types PHP provides 4 primitive data types Integer numbers Floating-point numbers String Boolean PHP provides 2 compound data types Array Object Lecture 6: Programming in PHP | SCK3633 Web Programming |

30 Using Arithmetic Operators Lecture 6: Programming in PHP | SCK3633 Web Programming |

31 WARNING: Using Variables with Undefined Values If you accidentally use a variable that does not have a value assigned to it will have no value (called a null value).When a variable with a null value is used in an expression PHP, PHP may not generate an error and may complete the expression evaluation. For example, the following PHP script will output x= y=4. Example : undef_var2.php Lecture 6: Programming in PHP | SCK3633 Web Programming |

32 PHP Precedence Rules PHP follows the precedence rules listed below. First it evaluates operators within First it evaluates operators withinparentheses. Next it evaluates multiplication and Next it evaluates multiplication and division operators. Finally it evaluates addition and Finally it evaluates addition and subtraction operators. Lecture 6: Programming in PHP | SCK3633 Web Programming |

33 PHP Precedence Rules For example, the first 2 statements evaluate to 80 while the last to 180. $x = 100 - 10 * 2; $x = 100 - 10 * 2; $y = 100 -(10 * 2); $y = 100 -(10 * 2); $z = (100 -10) * 2; $z = (100 -10) * 2; Lecture 6: Programming in PHP | SCK3633 Web Programming |

34 Strings Three ways for creating a string in PHP Double quatation mark ( "" ) Single quatation mark ('') Here document Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. Lecture 6: Programming in PHP | SCK3633 Web Programming |

35 Strings ….. Example 1: double and single quatation $a="World"; echo "1. Hello \t$a\n"; echo '2. Hi \t$a\n'; echo "\n"; $b=' Peace'; $c = $a.$b; echo "3. $a.$b = $c\n"; echo "4. \$a.\$b = $c\n"; Output ? Lecture 6: Programming in PHP | SCK3633 Web Programming |

36 Strings ….. Example 2: here document $a ='World'; $str = << { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/4168042/13/slides/slide_35.jpg", "name": "Strings …..", "description": "Example 2: here document $a = World ; $str = <<

37 Working with PHP String Variables Character strings are used in scripts to hold data Character strings are used in scripts to hold data such as customer names, addresses, product such as customer names, addresses, product names, and descriptions. names, and descriptions. Consider the following example. Consider the following example. $name="Christopher"; $name="Christopher"; $preference="Milk Shake"; $preference="Milk Shake"; $name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”. $name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

38 WARNING: Be Careful Not to Mix Variable Types Becareful not to mix string and numeric variable types. Becareful not to mix string and numeric variable types. For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”. For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

39 Using the Concatenate Operator The concatenate operator combines two separate string variables into one. For example, $fullname = $firstname. $lastname; $fullname = $firstname. $lastname; $fullname will receive the string values of $firstname and $lastname connected together. For example, $firstname = "John"; $lastname = "Smith"; $fullname = $firstname. $lastname; print ("Fullname=$fullname"); Lecture 6: Programming in PHP | SCK3633 Web Programming |

40 TIP; An Easier Way to Concatenate Strings. You can also use double quotation marks to create You can also use double quotation marks to create concatenation directly, concatenation directly, For example, For example, $Fullname2 = "$FirstName$LastName"; This statement has the same effect as $Fullname2 = $FirstName. “ ”. $LastName; Lecture 6: Programming in PHP | SCK3633 Web Programming |

41 The strlen() Function Most string functions require you to send them one or more arguments. Most string functions require you to send them one or more arguments. Arguments are input values that functions use in the processing they do. Arguments are input values that functions use in the processing they do. Often functions return a value to the script based on the input arguments. Often functions return a value to the script based on the input arguments. For example For example Lecture 6: Programming in PHP | SCK3633 Web Programming |

42 The strlen() Function Example This PHP script would output “Length=8”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

43 The trim() Function This function removes any blank characters This function removes any blank characters from the beginning and end of a string. from the beginning and end of a string. For example, consider the following script: For example, consider the following script: ?> Lecture 6: Programming in PHP | SCK3633 Web Programming |

44 The strtolower() and strtoupper() Functions These functions return the input string in all These functions return the input string in all uppercase or all lowercase letters, respectively. uppercase or all lowercase letters, respectively. For example, For example, The above would output “upper=NOW IS THE The above would output “upper=NOW IS THE TIME lower=now is the time”. TIME lower=now is the time”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

45 The substr() Function Substr has the following general format: Lecture 6: Programming in PHP | SCK3633 Web Programming |

46 The substr() Function The substr() function enumerates character positions starting with 0 (not 1), The substr() function enumerates character positions starting with 0 (not 1), For example, in the string “Homer”, the “H” would be position 0, the “o” would be position 1, the “m” position 2, and so on. For example, in the string “Homer”, the “H” would be position 0, the “o” would be position 1, the “m” position 2, and so on. For example, the following would output “Month=12 Day=25”. For example, the following would output “Month=12 Day=25”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

47 The substr() Function As another example, consider the following use of the substr() function As another example, consider the following use of the substr() function It does not include the third argument (and thus returns a substring from the starting position to the end of the search string). It does not include the third argument (and thus returns a substring from the starting position to the end of the search string). The above script segment would output The above script segment would output “Year=2002”. “Year=2002”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

48 Creating HTML Input Forms HTML Forms and not part of PHP language but important way to send data to scripts HTML Forms and not part of PHP language but important way to send data to scripts Lecture 6: Programming in PHP | SCK3633 Web Programming |

49 Starting And Ending HTML Forms You can create HTML forms by using the HTML and tags. You can create HTML forms by using the HTML and tags. Lecture 6: Programming in PHP | SCK3633 Web Programming |

50 Creating Form Buttons You can create submit and reset buttons by placing the following within & tags. You can create submit and reset buttons by placing the following within & tags. The submit button will be labeled “Click To Submit”. The reset button will be labeled “Erase and Restart”. Lecture 6: Programming in PHP | SCK3633 Web Programming |

51 A Full Example... The previous code can be executed at http://webwizard.aw.com/~phppgm/C2/form1.html Lecture 6: Programming in PHP | SCK3633 Web Programming |

52 Creating Text Input Boxes Text input boxes create a form element for receiving a single line of text input. Text input boxes create a form element for receiving a single line of text input. Will be 15 characters wide accepting a maximum of 20 characters. Will set a variable named fname with value of whatever the end-user enter. Lecture 6: Programming in PHP | SCK3633 Web Programming |

53 Creating Password Boxes Password boxes similar to text boxes except asterisks are displayed (instead of text input). Password boxes similar to text boxes except asterisks are displayed (instead of text input). Will be 15 characters wide accepting a maximum of 20 characters. Will set a variable named pass1 with value of whatever the end-user enter. Lecture 6: Programming in PHP | SCK3633 Web Programming |

54 Creating Text Areas The following creates a text area containing 4 rows and 50 columns. The following creates a text area containing 4 rows and 50 columns. The words “Your comments here” are the default text. The variable name Comments will be available to the form-handling script. Lecture 6: Programming in PHP | SCK3633 Web Programming |

55 Creating Radio Buttons Radio buttons are small circles that can select by clicking them with a mouse. Only one within a group can be selected at once. Radio buttons are small circles that can select by clicking them with a mouse. Only one within a group can be selected at once. The name argument must be the same for all radio buttons operating together. The value argument sets the variable value that will be available to the form processing script. Lecture 6: Programming in PHP | SCK3633 Web Programming |

56 Creating Check Boxes Check boxes are small boxes on a form that create Check boxes are small boxes on a form that create a check mark when the user clicks them. a check mark when the user clicks them. The above create four independent check boxes; that is, all four check box elements can be selected and each will set a value for a different variable name. Lecture 6: Programming in PHP | SCK3633 Web Programming |

57 Creating Check Boxes Might want to create a set of check boxes that use the same name argument. Might want to create a set of check boxes that use the same name argument. The value received by the form-processing script would be a comma-separated list of all items checked. Lecture 6: Programming in PHP | SCK3633 Web Programming |

58 Creating Selection Lists Creates a box with a scrolling list of one or more items that user can highlight and select. Creates a box with a scrolling list of one or more items that user can highlight and select. This HTML code creates four options formatted in a scrolling list. Only two of these options are displayed at the same time, and the user can select more than one option. Multiple selections are sent to the form- processing script as a comma separated list. Lecture 6: Programming in PHP | SCK3633 Web Programming |

59 Receiving Form Input into PHP Scripts To receive HTML form input into a PHP script: To receive HTML form input into a PHP script: Use a PHP var name that matches the variable Use a PHP var name that matches the variable defined in the form element’s name argument. defined in the form element’s name argument. For example, if form uses the following: For example, if form uses the following: Then form-handling PHP script could use a variable called $contact. Then form-handling PHP script could use a variable called $contact. If the user clicks the radio button, then If the user clicks the radio button, then $contact would = Yes $contact would = Yes Lecture 6: Programming in PHP | SCK3633 Web Programming |

60 Full Example Suppose your HTML form uses the following: Suppose your HTML form uses the following: Enter email address: Enter email address: Then can receive input as follows: Then can receive input as follows:1. 2. Receiving Input 2. Receiving Input 3. 4. Thank You: Got Your Input. 4. Thank You: Got Your Input. 5. Lecture 6: Programming in PHP | SCK3633 Web Programming |

61 Full Example... The previous code can be executed at http://webwizard.aw.com/~phppgm/C2/Form4Radio.html Lecture 6: Programming in PHP | SCK3633 Web Programming |

62 Register_Globals? Since PHP 4.2.1, the default PHP configuration is require a different mechanism to receive input for security reasons (than the one just shown). Since PHP 4.2.1, the default PHP configuration is require a different mechanism to receive input for security reasons (than the one just shown). Technical details: it is a PHP configuration option to turn REGISTER_GLOBALS OFF (new default) or ON in the php.ini configuration file. If your site has REGISTER_GLOBALS OFF you If your site has REGISTER_GLOBALS OFF you must use a different mechanism to receive HTML Form Variables. must use a different mechanism to receive HTML Form Variables. Lecture 6: Programming in PHP | SCK3633 Web Programming |

63 How can you tell if Register_Globals is OFF? Enter the following PHP script and run it. Enter the following PHP script and run it. Search through the output for Search through the output for REGISTER_GLOBALS and see if it is set to OFF or ON. REGISTER_GLOBALS and see if it is set to OFF or ON. If it is off you must use the following way to receive input data. If it is off you must use the following way to receive input data. Lecture 6: Programming in PHP | SCK3633 Web Programming |

64 Getting input data with Register_Globals OFF? To receive data with REGISTER_GOBALS OFF you use a special variable called $POST. To receive data with REGISTER_GOBALS OFF you use a special variable called $POST. $name $_POST[“name”]; Enclose in square bracket and then quotes Name of HTML form variable (note do not use $) Special PHP Global variable. Technically it is an associative array (covered in chptr 5.) PHP variable name that you want to receive the HTML form input. Lecture 6: Programming in PHP | SCK3633 Web Programming |

65 A Full Example... The previous code can be executed at http://webwizard.aw.com/~phppgm/C2/Form4Radio_NG.html The previous code can be executed at http://webwizard.aw.com/~phppgm/C2/Form4Radio_NG.html Lecture 6: Programming in PHP | SCK3633 Web Programming |

66 Conditional/Selection Statements Lecture 6: Programming in PHP | SCK3633 Web Programming |

67 Using Conditional Test Statements  Conditional statements provide a way for scripts to test for certain data values and then to react differently depending on the value found.  Same as C or C++  Will examine PHP If...Else Statements Switch statement Lecture 6: Programming in PHP | SCK3633 Web Programming |

68 if Statement Use an if statement to specify a test condition and a set of statements to run when a test condition is true. Lecture 6: Programming in PHP | SCK3633 Web Programming | if(expr) { statements } elseif(expr) { statements } else { statements } if(expr): statements elseif(expr): statements else: statements endif; Format 1:Format 2:

69 Example 1: What is the output if the $average is equal to 70? What is the output if the $average is equal to 70? if ($average > 69) { $Grade=“Pass”; print “Grade=$Grade ”; } print “Your average was $average”; Lecture 6: Programming in PHP | SCK3633 Web Programming |

70 Test Expressions Test expressions use test operators within their expressions.  Test operators work much like the expression operators.  Test operators evaluate to true or false Lecture 6: Programming in PHP | SCK3633 Web Programming |

71 PHP Test Operators Lecture 6: Programming in PHP | SCK3633 Web Programming |

72 Comparing Strings PHP represents strings using the ASCII code values.  ASCII provides a standard, numerical way to represent characters on a computer.  Every letter, number, and symbol is translated into a code number.  “A” is ASCII code 65, “B” is 66, “C” is 67, and etc.  Lowercase “a” is ASCII code 97, “b” is 98, “c” is 99, and etc.  ASCII “A” is less than ASCII “a”, “B” is less than “b”, and “c” is less than “d”.  ASCII characters have ASCII code values lower than letters. So ASCII character “1” is less than “a” or “A” Lecture 6: Programming in PHP | SCK3633 Web Programming |

73 Cont…  You can use == operator to check if one string is equal to another.  Also can use, = operators to compare string values using ASCII code values. Lecture 6: Programming in PHP | SCK3633 Web Programming |

74 Example 1: Example 2: $name1 = “George”; $name2 = “Martha”; if ($name1 == $name2) { print (“$name1 is equal to $name2”); } else { print (“$name1 is not equal to $name2”); } $name1 = “George”; $name2 = “Martha”; if ($name1 < $name2) { print (“$name1 is less than $name2”); } else { print (“$name1 is not less than $name2”); } Lecture 6: Programming in PHP | SCK3633 Web Programming |

75 elseif Clause  Use an elseif clause with an if statement to specify an additional test condition. Format:  The above script checks the elseif test expression when the test condition for the if statement is false. if (test expression) { one or more PHP statements } elseif (test expression) { one or more PHP statements } Lecture 6: Programming in PHP | SCK3633 Web Programming |

76 Cont…  One or more elseif clause can be used with an if statement. Example: if ($hour < 9) { print “Sorry, it is too early.”; } elseif {$hour < 12) { print Good morning. The hour is $hour. ”); print “How can we help you?”; } elseif ($hour < 13) { print “Sorry, we are out to lunch. ”; } elseif ($hour < 17) { print “Good afternoon. The hour is $hour. ”; print “How can we help you?”; } elseif ($hour <= 23) { print “Sorry, we have gone home already.”; } Lecture 6: Programming in PHP | SCK3633 Web Programming |

77 else Clause  Use an else clause with if and possibly one or more elseif clauses  specify set of statements to run when all the previous set test conditions are false.Format: if (test expression) { one or more PHP statements } else (test expression) { one or more PHP statements } Lecture 6: Programming in PHP | SCK3633 Web Programming |

78 Cont… Example 1: if ($count == 0) { print (“Time to reorder.”); $reorder=1; } elseif ($count == 1) { $reorder=1; print (“Warning: we need to start reordering.”); } elseif ($count > 1) { $reorder = 0; print (“We are OK for now.”); } else { print (“Illegal value for count = $count”); } Lecture 6: Programming in PHP | SCK3633 Web Programming |

79 Format 1: switch(expr) { case expr1: statements break; case expr2: statements break; default: statements break; } Format 2: switch(expr): case expr1: statements break; case expr2: statements break; default: statements break; endswitch; Lecture 6: Programming in PHP | SCK3633 Web Programming | switch Statement Use switch statement as another conditional test

80 Example 1: switch($rating) { case 1: $rated = “Poor”; print “The rating was $rated”; break; case 2: $rated = “Fair”; print “The rating was $rated”; break; case 3: $rated = “Good”; print “The rating was $rated”; break;default: print “Error: that rating does not exist”; ) Cont… Lecture 6: Programming in PHP | SCK3633 Web Programming |

81

82 PHP Looping  Scripts can use loop statements to repeat sections of code.  Same as C or C++  Advantages of loops include scripts can be more concise can write more flexible scripts  Activity 05 Lecture 6: Programming in PHP | SCK3633 Web Programming |

83 Cont…  while - loops through a block of code if and as long as a specified condition is true  do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true  for - loops through a block of code a specified number of times  foreach - loops through a block of code for each element in an array Lecture 6: Programming in PHP | SCK3633 Web Programming |

84 Repetition Statements Format 1: while(expr) { statements } while statement Format 2: while(expr): statements endwhile; Lecture 6: Programming in PHP | SCK3633 Web Programming |  If initially false, then the statements within the loop body will never run.  A bad idea to create an Infinite Loop  If the loop conditional test always true, then the loop will never end.  It will consume resources on the Web server and possibly slow down other server activity.

85 do { statements } while(expr); do-while statement Lecture 6: Programming in PHP | SCK3633 Web Programming |

86 Format 1: for(start_expr; cond_expr; iter_expr) { statements } for statement Format 2: for(start_expr; cond_expr; iter_expr): statements endfor; Lecture 6: Programming in PHP | SCK3633 Web Programming |

87 Format 1: foreach(array_expression as $value) { statements } foreach statement Format 2: foreach(array_expression as $value): statements endforeach; Format 3: associative array foreach(hash_array as $key=>$value){ statements } Lecture 6: Programming in PHP | SCK3633 Web Programming |

88 Cont… Example 1 : $brands = array("National", "MEC", "Khind", "Toshiba"); foreach ($brands as $value) echo $value,"\n"; Output??? Lecture 6: Programming in PHP | SCK3633 Web Programming |

89 Example 2 : $month["jan"] = "January"; $month["feb"] = "February"; $month["mar"] = "March"; $month["apr"] = "April"; foreach ($month as $key => $value) echo "Key: $key, Value: $value \n"; Output??? Lecture 6: Programming in PHP | SCK3633 Web Programming | Cont…

90 break and continue statements break is used to stop a loop. continue is used to skip the current iteration and go to the next iteration in a loop. Lecture 6: Programming in PHP | SCK3633 Web Programming |

91 Cont… Example : for ($i=1; $i<99; $i++) { if (($i%2)==0) continue; print ("$i is is an odd number\n"); if ($i>5) break; } Output??? Lecture 6: Programming in PHP | SCK3633 Web Programming |

92 Logical Test Operators  PHP supports a set of logical test operators you can use to create compound test expressions used within an if statement or a while statement to specify more than one test condition  Logical test operators: 1. &&-the AND operator.  Example: while($ctr < $max && $flag == 0) 2. ||-the OR operator.  Example: if($ctr != $max || $flag == 0) 3. !-the NOT operator.  Example: if(!=$flag == 0) Lecture 6: Programming in PHP | SCK3633 Web Programming |

93 PHP – Data transfer  Transferring data between client (web browser) to the server-side  Two method: Using form: POST method Through URL: GET method Lecture 6: Programming in PHP | SCK3633 Web Programming |

94 POST Method  The body of the message is sent as a stream of data (HTML form data)  Separated with the PHP URL in the FORM post URL  Client send data to servlet using HTML form element Lecture 6: Programming in PHP | SCK3633 Web Programming |

95 Cont…  Form tag

 Fill the TARGET value if form result have to display in a different frame  After coding all the form element (button, textfield, etc) FORM tag must be close using the equivalent end tag -  After coding all the form element (button, textfield, etc) FORM tag must be close using the equivalent end tag -  If you have multiple form in a single page every separate every form using the end tag Lecture 6: Programming in PHP | SCK3633 Web Programming |

96 GET method  The body of the message (the data) is appended to the PHP URL,  http://myserver.com/hello.php  Separated by a question mark  http://myserver.com/hello.php?  Followed by name-value pair which separated by equals sign  If value consist of more than one word, separate it using plus sign which the php will convert it to space character after parsing  name=john+doe  Every consecutive name-value pair will be separated using ampersand sign (&)  name=john+doe&id=007 Lecture 6: Programming in PHP | SCK3633 Web Programming |

97 Summary  Use conditional statements to test for certain conditions and based on the results of the test, to run specific script statements.  Loops expand the types of programming problems that you can solve and allow you to solve some programming problems much more concisely  Use logical AND (&&), OR (||) and NOT (!) operators to carry out compound tests.  Use POST and GET method to transfer data between client and the server side. Lecture 6: Programming in PHP | SCK3633 Web Programming |


Download ppt "PHP Programming Lecture 6: Programming in PHP | SCK3633 Web Programming |"

Similar presentations


Ads by Google