chapter 7 introduction to php5 part ii อ. ยืนยง กันทะเนตร...
TRANSCRIPT
CHAPTER 7Introduction to PHP5 Part II
อ. ยื�นยืง กั�นทะเนตรคณะเทคโนโลยื�สารสนเทศและกัารส��อสาร
มหาวิ�ทยืาล�ยืพะเยืา
1
Content
• PHP 5 if...else...elseif Statements• PHP 5 switch Statement• PHP 5 while Loops• PHP 5 for Loops• PHP 5 Functions• PHP 5 Arrays• PHP 5 Sorting Arrays• PHP 5 Global Variables - Superglobals
2
Content
• PHP 5 Form Handling• PHP 5 Form Validation• PHP 5 Forms - Required Fields• PHP 5 Forms - Validate E-mail and URL• PHP 5 Complete Form Example
3
PHP 5 if...else...elseif StatementsPHP - The if Statement<?php$t = 15;
if ($t < 20) { echo "Have a good day!";}?>
4
PHP - The if...else Statement<?php$t = 15;
if ($t < 20) { echo "Have a good day!";}else{ echo "Have a good night!";}?>
PHP 5 if...else...elseif Statements (cont.)PHP - The if...elseif....else Statement<?php$t = 15;
if ($t < 10) { echo "Have a good morning!";} elseif ($t < 20) { echo "Have a good day!";} else { echo "Have a good night!";}?>
5
PHP 5 switch StatementThe PHP switch Statement<?php$favcolor = "red";
switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; default: echo "Your favorite color is neither red, blue, or green!";}?>
6
PHP 5 while LoopsThe PHP while Loop<?php $x = 1;
while($x <= 5) { echo "The number is: $x <br>"; $x++;} ?>
7
The PHP do...while Loop<?php $x = 1;
do { echo "The number is: $x <br>"; $x++;} while ($x <= 5);?>
PHP 5 for LoopsThe PHP for Loop<?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>";} ?>
8
The PHP foreach Loop<?php $colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) { echo "$value <br>";}?>
PHP 5 FunctionsCreate a User Defined Function in PHPSyntax
function functionName() { code to be executed;}
Example<?phpfunction writeMsg() { echo "Hello world!";}writeMsg(); // call the function?>
9
PHP 5 Functions (cont.)PHP Function ArgumentsExample
<?phpfunction familyName($fname) { echo "$fname br>";}
familyName("Jani");familyName("Hege"); //output Jani Hege?>
10
PHP 5 Functions (cont.)PHP Default Argument ValueExample
<?phpfunction setHeight($minheight = 50) { echo "The height is : $minheight <br>";}
setHeight(350);setHeight(); // will use the default value of 50setHeight(135);setHeight(80);?>
11
PHP 5 Functions (cont.)PHP Functions - Returning valuesExample
<?phpfunction sum($x, $y) { $z = $x + $y; return $z;}
echo "5 + 10 = " . sum(5, 10) . "<br>";echo "7 + 13 = " . sum(7, 13) . "<br>";echo "2 + 4 = " . sum(2, 4);?>
12
PHP 5 ArraysWhat is an Array?• An array is a special variable, which can hold more than one
value at a time.
$cars1 = "Volvo";$cars2 = "BMW";$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
13
PHP 5 Arrays (cont.)Create an Array in PHP
array();Example
$cars = array("Volvo", "BMW", "Toyota");or the index can be assigned manually:$cars[0] = "Volvo";$cars[1] = "BMW";$cars[2] = "Toyota";
14
PHP 5 Arrays (cont.)Get The Length of an Array - The count() Function
count();Example
<?php$cars = array("Volvo", "BMW", "Toyota");echo count($cars);?> //output 3
15
PHP 5 Arrays (cont.)Loop Through an Indexed ArrayExample
<?php$cars = array("Volvo", "BMW", "Toyota");$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>";
}?>
16
PHP 5 Arrays (cont.)PHP Associative ArraysExample
<?php$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");echo "Peter is " . $age['Peter'] . " years old.";?>
17
Loop Through an Associative ArrayExample
<?php$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";
} ?>
PHP 5 Sorting ArraysPHP - Sort Functions For ArraysIn this chapter, we will go through the following PHP array sort functions:• sort() - sort arrays in ascending order• rsort() - sort arrays in descending order• asort() - sort associative arrays in ascending order, according
to the value• ksort() - sort associative arrays in ascending order, according
to the key• arsort() - sort associative arrays in descending order,
according to the value• krsort() - sort associative arrays in descending order,
according to the key18
PHP 5 Sorting Arrays (cont.)
Sort Array in Ascending Order - sort()<?php
$cars = array("Volvo", "BMW", "Toyota");sort($cars);
?>
19
Sort Array in Descending Order - rsort()<?php
$cars = array("Volvo", "BMW", "Toyota");rsort($cars);
?>
PHP 5 Sorting Arrays (cont.)Sort Array (Ascending Order), According to Value - asort()<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");asort($age);
?>
20
Sort Array (Ascending Order), According to Key - ksort()<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");ksort($age);
?>
PHP 5 Sorting Arrays (cont.)Sort Array (Descending Order), According to Value - arsort()<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");arsort($age);
?>
21
Sort Array (Descending Order), According to Key - krsort()<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");krsort($age);
?>
PHP 5 Global Variables - Superglobals
PHP Global Variables - SuperglobalsSeveral predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.The PHP superglobal variables are:• $GLOBALS• $_SERVER• $_REQUEST• $_POST• $_GET• $_FILES• $_ENV• $_COOKIE• $_SESSION
22
PHP 5 Global Variables - Superglobals (cont.)
PHP $_POST<html><body><form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"></form><?phpif ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; }}?></body></html>
23
PHP 5 Global Variables - Superglobals (cont.)
PHP $_GET //test_get.html<html><body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body></html>
24
PHP $_GET //test_get.php<html><body>
<?php echo "Study " . $_GET['subject'] . " at " . $_GET['web'];?>
</body></html>
PHP 5 Form Handling
PHP - A Simple HTML Form $_GET <html><body>
<form action="welcome_get.php" method=“get">Name: <input type="text" name="name"><br>E-mail: <input type="text" name="email"><br><input type="submit"></form>
</body></html>
25
PHP - A Simple HTML Form<html><body>
Welcome <?php echo $_GET["name"]; ?><br>Your email address is: <?php echo $_GET["email"]; ?>
</body></html>
// outputWelcome nameYour email address is [email protected]
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP 5 Form Handling
PHP - A Simple HTML Form $_POST <html><body>
<form action="welcome_post.php" method=“post">Name: <input type="text" name="name"><br>E-mail: <input type="text" name="email"><br><input type="submit"></form>
</body></html>
26
PHP - A Simple HTML Form<html><body>
Welcome <?php echo $_POST["name"]; ?><br>Your email address is: <?php echo $_POST["email"]; ?>
</body></html>
// outputWelcome nameYour email address is [email protected]
PHP 5 Form Validation
27
PHP 5 Form Validation (cont.)
28
// formValidate.php<?php
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]);}
function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;}?>
PHP 5 Form Validation (cont.)
29
// formValidate.php
<h2>PHP Form Validation Example</h2><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <br><br> <input type="submit" name="submit" value="Submit"> </form>
PHP 5 Form Validation (cont.)
30
// formValidate.php
<?phpecho "<h2>Your Input:</h2>";echo $name;echo "<br>";echo $email;echo "<br>";echo $website;echo "<br>";echo $comment;echo "<br>";echo $gender;?>
PHP 5 Forms - Required Fields
31
// formValidate.php
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); }
if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); }
PHP 5 Forms - Required Fields (cont.)
32
// formValidate.phpif (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); }
if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); }
if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); }}?>
PHP 5 Forms - Required Fields (cont.)
33
// formValidate.php<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">Name: <input type="text" name="name"><span class="error">* <?php echo $nameErr;?></span><br><br>E-mail:<input type="text" name="email"><span class="error">* <?php echo $emailErr;?></span><br><br>Website:<input type="text" name="website"><span class="error"><?php echo $websiteErr;?></span><br><br><label>Comment: <textarea name="comment" rows="5" cols="40"></textarea><br><br>Gender:<input type="radio" name="gender" value="female">Female<input type="radio" name="gender" value="male">Male<span class="error">* <?php echo $genderErr;?></span><br><br><input type="submit" name="submit" value="Submit"> </form>
PHP 5 Forms - Validate E-mail and URL
34
// formValidate.php
PHP - Validate Name$name = test_input($_POST["name"]);if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; }
// formValidate.php
PHP - Validate E-mail$email = test_input($_POST["email"]);if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
PHP 5 Forms - Validate E-mail and URL (cont.)
35
// formValidate.php
PHP - Validate URL$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; }
PHP 5 Complete Form Example
36
// formValidate.php
PHP - Keep The Values in The FormName: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
Gender:<input type="radio" name="gender"<?php if (isset($gender) && $gender=="female") echo "checked";?>value="female">Female<input type="radio" name="gender"<?php if (isset($gender) && $gender=="male") echo "checked";?>value="male">Male
37
THE END