1
CS428 Web Engineering
Lecture 11
Control Structures & Loops, Database Connectivity
• Format:
if (expression) statement;
• Example:
if ($a > $b)
echo “a is larger than b”;
• or (if you have more than one line of code)
if ($a > $b){
echo “a is larger than b”;
EXAMPLE
• <?php
$a = 4; $b = 3;
if ($a > $b){
echo “a is larger than b”; }
?>
EXAMPLE
• <?php
$a = 3; $b = 4;
if ($a > $b) {
echo “a is larger than b”; }
if ($a < $b){
echo “a is not larger than b”; }
• <?php
$a = 3; $b = 4;
if ($a > $b) {
echo “a is larger than b”; }
else {
echo “a is not larger than b”; }
EXAMPLE
• How to deal with different cases:
• <?php
$a = 4; $b = 4;
if ($a > $b) {
echo “a is larger than b”; } elseif ($a == $b) {
echo “a equals to b”; } else {
echo “a is smaller than b”; }
LOGICAL OPERATORS (AND)
• <?php $a = 5; $b = 4; ?>
<?php $c = 20; $d = 1;
if (($a > $b) && ($c > $d)){
echo “a is larger than b AND ”;
echo “c is larger than d ”; }
LOGICAL OPERATORS (OR)
• <?php $a = 5; $b = 4; ?>
<?php $c = 1; $d = 20;
if (($a > $b) || ($c > $d)){
echo “a is larger than b OR ”;
echo “c is larger than d ”; }
EXAMPLE
• If variable a is not set, then set equals to 100.
• <?php
$a = 5; $b = 4;
?>
<?php
if (!isset($a)){ $a = 100;
}
echo $a;
EXAMPLE
• If variable a is not set, then set equals to 100. • <?php
$a = 5; $b = 4; ?>
<?php
unset($a);
if (!isset($a)){ $a = 100;
}
• If a is integer, then set its type equals to string. • <?php
$a = 5; $b = 4; ?>
<?php
if (is_int($a)) {
settype($a, “string”);
}
echo gettype($a);
Logical Expressions: Switch
• <?php $a = 3; ?> • <?php
switch ($a){ case 0:
echo “a equals 0”;
break; case 1:
echo “a equals 1”;
break; case 2:
echo “a equals 2”;
break; default:
echo “a is not 0, 1 or 2”;
break;
}
LOOPS
• Loops allow us to execute the code until the condition is satisfied. There are three main kinds of loops:
• while Loops
• for Loops
WHILE LOOPS
• The format of while loops is as under:
while (expression)
statement;
EXAMPLE
• <?php
$count = 0;
while ($count <= 10) {
echo $count . “, ”; $count++;
}
echo “<br /> Count: {$count}”;
EXAMPLE
• <?php$count = 0;
while ($count <= 10) {
if ($count == 5) {
echo “FIVE”;
} else {
echo $count . “, ”;
}
$count++; }
echo “<br /> Count: {$count}”;
FOR LOOP
• The format of for loops is as under:
for (expr1, expr2, expr3)
statement;
• The expression would be boolean statement, • Expression1 could be initializing statement. • Expression2 could be condition/test.
EXAMPLE
• <?php
for ($count = 0; $count <= 10; $count++ ) {
echo $count . “, ”; }
FOREACH LOOP
• The format of foreach loops is as under:
foreach ($array as $value)
statement;
• The boolean test foreach loop is, do we have items still left in array. Foreach loop will go through every single element of an array.
• Foreach loop only works with array.
EXAMPLE
• <?php
$ages = array(4, 8, 15, 17, 23, 42);
?>
<?php
// using each value
foreach ($ages as $age) {
echo $age . “, ”; }
• Syntax for associative array
• Foreach loop can take each array as a key
value pair.
EXAMPLE
• <?php$ages = array(4, 8, 15, 16, 23, 42); ?>
• <?php
// using each key => value pair
// key for 4 is 0, key for 8 is 1 and so on… foreach ($ages as $position => $age) {
echo $position . “: ” . $age . “<br/>”; }
• <?php
$prices = array(“Brand new computer”=>2000, “1 month in lynda.com training center”=>25, “Learning PHP”=> “priceless”);
foreach ($prices as $key => $value) {
if (is_int($value)) {
echo $key . “: $” . $value . “<br/>”; } else {
echo $key . “: ” . $value . “<br/>”; }
}
LOOPS: Continue
• If we didn’t want to print let say 5 • <?phpfor ($count=0; $count <=10; $count++) { if ($count == 5) {
continue;
}
echo $count . “, ”; }
?>
• Lets say we are looking through, a list of students in a database. We can perform lots of complex
action on it.
• But the very first thing we check, whether or not the student is fresh man, s/w engineer jr. or
senior.
• If we turns out, the student is fresh man, we don’t want anything else.
LOOPS: Break
• If we didn’t want to print before 5 • <?phpfor ($count=0; $count <=10; $count++) { if ($count == 5) {
break;
}
echo $count . “, ”; }
?>
• If we don’t want comma (,) at the end of last number.
• <?php
for ($count = 0; $count <= 10; $count++) { echo $count;
if ($count == 10) {
break;
}
echo “, ”; }
?>
POINTERS
• Computer maintains the pointer, that’s
points to the current value of an array. By default its always the first value.
EXAMPLE
• <?php
$ages = array(4, 8, 15, 16, 23, 42);
?>
<?php
echo “1: ” . current($ages) . “<br />”;
// that will give us, the current place, the pointer is pointing.
?>
• <?php
$ages = array(4, 8, 15, 16, 23, 42); ?>
<?php
echo “1: ” . current($ages) . “<br />”;
next($ages); // that will advance the pointer.
echo “2: ” . current($ages) . “<br />”; ?>
• <?php
$ages = array(4, 8, 15, 16, 23, 42);
?>
<?php
echo “1: ” . current($ages) . “<br />”;
next($ages);
echo “2: ” . current($ages) . “<br />”;
reset($ages);
echo “3: ” . current($ages) . “<br />”;
?>
• Output: 1: 4 2: 8
EXAMPLE
• <?php
$ages = array(4, 8, 15, 16, 23, 42);
?>
<?php
// while loop that moves the array pointer
while ($age = current($ages)) {
echo $age . “, ”;
next($ages);
}
?>
NOTE
• When we start working with databases, this is the format we going to take. We
grasp bunch of data out of our database. That’s going to be an array. We can than move through by assigning a value to it.
• Moving through each time, letting the
pointer update its own. So its keep moving on the database. Keep working on each
• Let say we have a database of products. We can have product1 output. And then advance to next product in the database. The next item in the array and output that. It makes lot more sense when we are
• In order to have really full featured application. We are going to need to incorporate a
database.
• We can store lots of information in database, search through it. Added it, updated. Keep it there for long period of time. There are so
many benefits of using database.
CRUD
• CRUD is acronym and it stands for…
CRUD
Create
,
Read
,
Update
,
Delete
• We create records in the database.
• We read records back in the database.
• We update records in the database.
SQL SELECT (Read)
• Format:
• SELECT * FROM table
WHERE column1 = ‘some_text’
SQL INSERT (Create)
• Format:
SQL UPDATE (Update)
• Format:
• UPDATE table
SET column1 = ‘some_text’
SQL DELETE (Delete)
• Format:
• DELETE FROM table
CREATE COMMAND
• CREATE DATABASE widget_corp;
• USE widget_corp;
• CREATE TABLE subjects (
id int(11) NOT NULL auto_increment,
menu_name varchar(30) NOT NULL,
position int(3) NOT NULL,
visible tinyint(1) NOT NULL,
PRIMARY KEY (id)
INSERT COMMAND
• INSERT INTO subjects (menu_name, position, visible) VALUES (‘About Widget Corp’, 1, 1);
• SELECT * FROM subjects;
• INSERT INTO subjects (menu_name, position, visible) VALUES (‘Products’, 2, 1);
• INSERT INTO subjects (menu_name, position, visible) VALUES (‘Services’, 3, 1);
SELECT COMMAND
• SELECT * FROM subjects WHERE visible = 1
ORDER BY position ASC/DESC;
• SELECT id, menu_name FROM subjects WHERE visible = 1
UPDATE COMMAND
• UPDATE subjects SET visible = 1
PHPMyAdmin
• www.phpmyadmin.net
• It is already included in WAMP/XAMP one package.
Using PHPMyAdmin
• It enables you to access your MySQL database through a GUI. You can easily do the following:
• Drop and create databases
• Create, edit and delete tables • Create, edit and delete fields • Enter any MySQL statements • View and Print table structure • Generate PHP code
PHP Database Interaction in
FOUR steps
1. Create a database connection
2. Perform database query
COMMONLY USED FUNCTIONS
• mysqli_connect(“hostname”,”user”,”pass”, “dbname”);
• mysqli_query(handle, query”);
• mysqli_num_rows(result variable from query);
Connects to MySQL server.
Execute database query
• mysqli_fetch_array(“result variable from query”);
• mysqli_fetch_assoc(“result variable from query”)
Used to return several rows of the entire
results of a database query
Used to return several rows of the entire
• mysqli_error();
• md5(string);
Shows the error message that has
been returned directly from MySQL server.
It uses is to encrypt a string. It returns 32 characters
md5()
• Example:
$str = “Hello”; echo md5($str);
• Output:
date()
• Example:
echo date(“Y”); // 2015 (year) echo date(“m”); // 12 (month) echo date(“d”); // 27 (day)
echo date(“Y-m-d”); // 2015-01-27 echo date(“d/m/y”); // 28/12/15
echo date(“F d, Y”); // January 28, 2015 echo date(“F j, Y, h:i:s a”);
STEP 1
• <?php
// 1. Create a database connection
$connection = mysqli_connect(“localhost”, “root”, “password”,
“widget_corp”); if (!$connection) {
die(“Database connection failed: ” . mysqli_error()); }
?>
<html> …
</html>
STEP 2
• Step 1 (create a database connection) • <html>
<head></head> <body>
<?php
// 3. Perform database query
$query = “SELECT * FROM subjects”;
$result = mysqli_query($connection, $query); if (!result) {
die(“Database query failed: ” . mysqli_error()); }
?>
STEP 3
• <html> …
<?php
// 2. Perform database query
$query = “SELECT * FROM subjects”;
$result = mysqli_query($connection, $query); if (!result) {
die(“Database query failed: ” . mysqli_error()); }
// 3. Use returned data
while ($row = mysqli_fetch_array($result)) { echo $row[1] . “ ” . $row[2] . “<br />”;
}
?>
STEP 4
• Step 1 • <html>
<head></head> <body>
Step 2 Step 3 </body> </html> <?php
// 5. Close connection
EXAMPLE
• Create a database name school in MySQL.
• Create a table name result, with following fields sId, sName and Marks.
EXAMPLE: STEP 1
• Create connection
<?php
// 1. create a connection
$connection =
mysqli_connect(“localhost”,”root”,””,”school”); if(!connection) {
die(“database connection failed” . mysqli_error()); }
EXAMPLE: STEP 2
• Step 1 (create a database connection) • <html>
<head></head> <body>
<?php
// 2. Perform database query
$query = “SELECT * FROM result”;
$result = mysqli_query($connection, $query); if (!$result) {
die(“Database query failed: ” . mysqli_error()); }
if(mysqli_num_rows($result <= 0)){ die(“No record found”);
} ?>
EXAMPLE: STEP 4
• Step 1 (create a database connection) • Step 2 (select a database to use)
• <html> …
<?php
Step 3 (perform database query)
// 4. Use returned data
while ($row = mysqli_fetch_array($result)) { echo $row[0] . “<br />”;
echo $row[1] . “<br />”; echo $row[2] . “<br />”; }
?>
EXAMPLE: STEP 5
• Step 1 • Step 2 • <html>
<head></head> <body>
Step 3 Step 4 </body> </html> <?php
// 5. Close connection