Lecture 4- Programing with PHP
Lecture 4- Programing with PHP
OUTLINE
1. Creating and handling forms
2. Conditional statements
3. Iteration statements
4. Q & A
PHP CONTROL STRUCTURES-
INTRODUCTION
Control structures determine the flow of program
execution.
Three categories;
• Sequence – default control structure where the statements
are executed in the order they appear in the code.
• Selection – IF and switch case
• Iteration/Loop – while, do while and for loops
SELECTION CONTROL STRUCTURE
In PHP IF statement consist of:
• if statement - use this statement to execute some code only
if a specified condition is true
• if...else statement - use this statement to execute some
code if a condition is true and another code if the condition is
false
• if...elseif....else statement - use this statement to select one
of several blocks of code to be executed
THE IF STATEMENT
The PHP if statement is very similar to other
programming languages use of the if statement.
Example: Think about the decisions you make before
you go to sleep. If you have something to do the next
day, say go to work, school, or an appointment, then
you will set your alarm clock to wake you up.
Otherwise, you will sleep in as long as you like!
The PHP if statement tests to see if a value is true, and
if it is a segment of code will be executed.
The if statement is necessary for most programming,
thus it is important in PHP.
THE IF STATEMENT CONT..
if statement
if_statement.php
if (condition) { <body>
// Do something! <?php
$my_name = "anotherguy";
} if ($my_name == "someguy" )
if (condition) echo "Your name issomeguy!<br />";
?>
code to be executed if condition </body>
is true;
Display
How about A False If
Statement
if_statements_part_1.php
THE IF...ELSE STATEMENT
Use the if....else statement to execute some code if a
condition is true and another code if a condition is false
syntax
<body>
if (condition) { <?php
$grade = 90;
// Do something!
if (grade>=40)
} else { echo “you passed”;
// Do something else! else
} echo “you didn’t pass”;
<?php ?>
$d=date("D"); </body>
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
IF..ELSEIF…ELSE STATEMENT
Use the if....elseif...else statement to select one of
several blocks of code to be executed.
An elseif clause allows you to add more conditions:
if_statement2.php
if (condition1) { <body>
// Do something! <?php
} elseif (condition2) { $grade = 90;
// Do something else! if (grade>=80)
} else { echo “very well done”,
// Do something different! elseif (grade>=60)
echo “you passed”;
}
else
echo “you didn’t pass”;
?>
</body>
if_statements_part_2.php
CONDITIONAL
STATEMENT
Others:
o True, TRUE, true
always true
o isset($x): returns true
if a value was set for
$x (i.e. different from NULL)
o $var returns true if
$var value is different
from:
0
Empty string
FALSE
NULL
CONDITIONAL STATEMENT
switch statement
switch_statement.php
switch ($variable) { <?php
…
case 'value1’: switch ($gender) {
// Do this. case 'Male':
break; echo "Dear Mr. Doe";
case 'value2’: break;
// Do this instead. case 'Female':
break; echo "Dear Ms. Doe";
default: break;
default:
// Do this then.
echo "Dear Sir/Madam. Doe";
break; break;
} } ?>
switch.php
PHP - LOOPS
Repetitive tasks are always a burden to us. Most often
these repetitive tasks are conquered in the loop.
The idea of a loop is to do something over and over
again until the task has been completed.
PHP support three types of loops:
While loop
do while loop
for loop
PHP WHILE LOOP STATEMENTS
The function of the while loop is to
do a task over and over as long as
the specified conditional statement
is true.
A flowchart
representation
of how PHP
handles a
while loop.
PHP WHILE LOOP STATEMENTS
How while loop functions
A flowchart
representation
of how PHP
handles a for
PHP FOR LOOP STATEMENTS
How for loop functions
Example
1. Set a counter variable to some initial $brush_price = 5;
value. echo "<table border=\"1\" align=\"center\">";
2. Check to see if the conditional echo "<tr><th>Quantity</th>";
statement is true. echo "<th>Price</th></tr>";
3. Execute the code within the loop. for ( $counter = 10; $counter <= 100; $counter +=
4. Increment a counter at the end of each 10) {
echo "<tr><td>";
iteration through the loop.
echo $counter;
echo "</td><td>";
echo $brush_price * $counter;
echo "</td></tr>";
}
echo "</table>";
PHP - DO WHILE LOOP
A "do while" loop is a slightly modified version of the
while loop.
While Loops the conditional statement is checked
comes back true then the code within the while loop is
executed. If the conditional statement is false then the
code within the loop is not executed.
On the other hand, a do-while loop always executes its
block of code at least once. This is because the
conditional statement is not checked until after the
contained code has been executed.
COMPARISON
while Do while
$cookies = 0; $cookies = 0;
while($cookies > 1){ do {
echo "Mmmmm...I love cookies! echo "Mmmmm...I love
*munch munch munch*"; cookies! *munch
} munch munch*"; }
while ($cookies > 1);
USING PHP WITH HTML FORMS
A very common application of PHP is to have an HTML
form gather information from a website's visitor and
then use PHP to do process that information.
Two steps are involved:
first you create the HTML form itself, and
then you create the corresponding PHP script that will
receive and process the form data
An HTML form is created using the form tags and
various elements for taking input
In terms of PHP, the most important attribute of your
form tag is action, which dictates to which page the
form data will be sent.
The second attribute—method—has its own issues but
post is the value you’ll use most frequently
CREATING AND HANDLING FORMS
Creating an HTML form: example
form.html
<body>
<form action="handle_form.php" method="post">
Name: <input type="text" name="name" size="20" maxlength= "40" /><br />
Gender:<input type="radio" name="gender" value="M" /> Male
<input type="radio" name="gender" value="F" /> Female<br />
Age: <select name="age">
<option value="0-29">Under 30</option>
<option value="30-60">Between 30 and 60</option>
</select><br />
<input type= "submit" name="submit" value="Submit My Information" /><br>
</form>
</body>
Output
form.html
handle_form.php
CREATING AND HANDLING FORMS
Handling an HTML form
input fields are accessible via: $_REQUEST[‘field-name‘].
e.g. $_REQUEST[‘age'].
Output
VALIDATING FORM DATA
Two main goals
a) validate if something was entered or selected in form
elements
o empty() : validate if something was typed into a text input
• empty value = empty string, 0, NULL, or FALSE.
form1.html
handle_form1.php
VALIDATING FORM DATA
Some triimportant functions
trim(): eliminates leading and trailing spaces
form2.html
handle_form2.php
patterns.php
$name = $_REQUEST['name’];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
• Note the space between Z and ]
MORE EXAMPLES
• Check Username 5 to 10 lowercase letters?
$name = $_REQUEST['name’];
$pattern = '/^[a-z]{5,10}$/';
if (!preg_match($pattern, $name))
{
echo "<p>$username is invalid.</p>";
}
Check Social Security Number 123-45-6789
$pattern = '/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/';
if (!preg_match($pattern, $ssn))
{
echo "<p>$ssn is invalid.</p>";
}
EMAIL VALIDATION
• The Most Basic common pattern
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]
+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i",$email))
PRACTICE
Create an html form and a php web page to do the
following:
1. Display a form to the user to enter his/her name and GPA
2. Check if a name was entered and that the GPA is valid (is a
number between 0 and 4)
3. If any of the two conditions is not true
a. print an error message to the user explaining what the error
is (e.g. “the user name should not be empty” and “the GPA
should be a number between 0 and 4”)
b. Allow the user to go back to the form
4. If both conditions are true, Display a message thanking the user;
e.g. “Thank you Noora for sending your request. Your GPA ‘3’ was
recorded. We will contact you soon”
PRACTICE
Steps
1. Display the form (practice.html) send data to practice.php
2. In the practice.php
a) Declare two variables ($name and $gpa) to read the inputs
b) Check the name if empty, display error message stating that “the name
should not be empty”
c) If name not empty, check gpa if GPA not valid (i.e. not a number or not
between 0 and 4), display error message stating that “the GPA should be
a number between 0 and 4.”
d) If GPA valid, display a message thanking the user; e.g.
ANY QUESTIONS?
45
REFERENCES
• Book
• “PHP and MySQL for Dynamic Web Sites” 4th edition,
Chapters 2 & 14
• PHP
• https://www.w3schools.com/php/default.asp
• http://php.net/manual/en/langref.php
A Live Regular Expression Tester for PHP
• https://regex101.com
•
46