• No results found

Lec 11 PHP - III.pptx

N/A
N/A
Protected

Academic year: 2020

Share "Lec 11 PHP - III.pptx"

Copied!
64
0
0

Loading.... (view fulltext now)

Full text

(1)

1

CS428 Web Engineering

Lecture 11

Control Structures & Loops, Database Connectivity

(2)

• Format:

if (expression) statement;

• Example:

if ($a > $b)

echo “a is larger than b”;

(3)

• or (if you have more than one line of code)

if ($a > $b){

echo “a is larger than b”;

(4)

EXAMPLE

• <?php

$a = 4; $b = 3;

if ($a > $b){

echo “a is larger than b”; }

?>

(5)

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”; }

(6)

• <?php

$a = 3; $b = 4;

if ($a > $b) {

echo “a is larger than b”; }

else {

echo “a is not larger than b”; }

(7)

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”; }

(8)

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 ”; }

(9)

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 ”; }

(10)

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;

(11)

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;

}

(12)

• 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);

(13)

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;

}

(14)

LOOPS

• Loops allow us to execute the code until the condition is satisfied. There are three main kinds of loops:

• while Loops

• for Loops

(15)

WHILE LOOPS

• The format of while loops is as under:

while (expression)

statement;

(16)

EXAMPLE

• <?php

$count = 0;

while ($count <= 10) {

echo $count . “, ”; $count++;

}

echo “<br /> Count: {$count}”;

(17)

EXAMPLE

• <?php

$count = 0;

while ($count <= 10) {

if ($count == 5) {

echo “FIVE”;

} else {

echo $count . “, ”;

}

$count++; }

echo “<br /> Count: {$count}”;

(18)

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.

(19)

EXAMPLE

• <?php

for ($count = 0; $count <= 10; $count++ ) {

echo $count . “, ”; }

(20)

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.

(21)

EXAMPLE

• <?php

$ages = array(4, 8, 15, 17, 23, 42);

?>

<?php

// using each value

foreach ($ages as $age) {

echo $age . “, ”; }

(22)

Syntax for associative array

Foreach loop can take each array as a key

value pair.

(23)

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/>”; }

(24)

• <?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/>”; }

}

(25)

LOOPS: Continue

• If we didn’t want to print let say 5 • <?php

for ($count=0; $count <=10; $count++) { if ($count == 5) {

continue;

}

echo $count . “, ”; }

?>

(26)

• 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.

(27)

LOOPS: Break

• If we didn’t want to print before 5 • <?php

for ($count=0; $count <=10; $count++) { if ($count == 5) {

break;

}

echo $count . “, ”; }

?>

(28)

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 “, ”; }

?>

(29)

POINTERS

• Computer maintains the pointer, that’s

points to the current value of an array. By default its always the first value.

(30)

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.

?>

(31)

• <?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 />”; ?>

(32)

• <?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

(33)

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);

}

?>

(34)

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

(35)

• 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

(36)

• 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.

(37)

CRUD

• CRUD is acronym and it stands for…

CRUD

Create

,

Read

,

Update

,

Delete

(38)

• We create records in the database.

• We read records back in the database.

• We update records in the database.

(39)

SQL SELECT (Read)

• Format:

• SELECT * FROM table

WHERE column1 = ‘some_text’

(40)

SQL INSERT (Create)

• Format:

(41)

SQL UPDATE (Update)

• Format:

• UPDATE table

SET column1 = ‘some_text’

(42)

SQL DELETE (Delete)

• Format:

• DELETE FROM table

(43)

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)

(44)

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);

(45)

SELECT COMMAND

• SELECT * FROM subjects WHERE visible = 1

ORDER BY position ASC/DESC;

• SELECT id, menu_name FROM subjects WHERE visible = 1

(46)

UPDATE COMMAND

• UPDATE subjects SET visible = 1

(47)

PHPMyAdmin

www.phpmyadmin.net

• It is already included in WAMP/XAMP one package.

(48)

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

(49)
(50)

PHP Database Interaction in

FOUR steps

1. Create a database connection

2. Perform database query

(51)

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

(52)

• 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

(53)

• 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

(54)

md5()

• Example:

$str = “Hello”; echo md5($str);

• Output:

(55)

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”);

(56)

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>

(57)

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()); }

?>

(58)

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 />”;

}

?>

(59)

STEP 4

• Step 1 • <html>

<head></head> <body>

Step 2 Step 3 </body> </html> <?php

// 5. Close connection

(60)

EXAMPLE

• Create a database name school in MySQL.

• Create a table name result, with following fields sId, sName and Marks.

(61)

EXAMPLE: STEP 1

• Create connection

<?php

// 1. create a connection

$connection =

mysqli_connect(“localhost”,”root”,””,”school”); if(!connection) {

die(“database connection failed” . mysqli_error()); }

(62)

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”);

} ?>

(63)

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 />”; }

?>

(64)

EXAMPLE: STEP 5

• Step 1 • Step 2 • <html>

<head></head> <body>

Step 3 Step 4 </body> </html> <?php

// 5. Close connection

References

Related documents

Based on language needs analysis of Elementary Students grade 1, 2, and 3, Balinese vocabulary teaching model that is based on natural semantic meta-language theory ( NSM ).. In

Another 1/8 of the athletes (12,50%) treated the knee ligament injury mainly with strengthening with special therapeutic exercises, combined with physiotherapies,

Expands eligibility for Medicaid and the State Children's Health Insurance Program (SCHIP). Creates an insurance exchange or connector that would offer a choice of private plans and

The current research employed a quantitative method with Structural Equation Modeling Partial Least Square (SEM-PLS) analysis. The samples in this research were

So, if the propensity for criminal behavior is ignored in the counseling process because racial or cultural factors are not considered, then it is conceivable that a

To broaden the methodology for single individual video grouping to multi individuals action

Through the policy of Potikelek market building in Jayawijaya regency, it was expected that it could reduce the trading monopoly conducted by non-Papua traders.. However, it

Abstract: This study investigated the antifungal activities of Trichoderma species against Pythium aphanidermatum; determined and measured the induction of defense enzymes