connecting php and mysql - queen's...

36
Connecting PHP and MySQL 1

Upload: ngokhuong

Post on 10-Sep-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

Connecting PHP and MySQL

1

Outline

• PHP Loops

• PHPMyAdmin

• Introducing SQL

• Connecting Database from PHP

• Exercises

2

Loops

• A loop statement is a control structure that repeatedly executes a statement or a series of statements while a specific condition is TRUE or until a specific condition becomes TRUE

• Three different types of loops are:

• while statements

• do...while statements

• for statements

3

While Loop

• Tests the condition prior to executing the series of statements at each iteration of the loop

• The syntax for the while statement is: while (conditional expression) {

statement(s);

}

• As long as the conditional expression evaluates to TRUE, the statement or command block that follows executes repeatedly

4

While Loop • Each repetition of a looping statement is called an iteration.

• A while statement keeps repeating until its conditional expression evaluates to FALSE

• A counter is a variable that increments or decrements with each iteration of a loop statement.

• In an infinite loop, a loop statement never ends because its conditional expression is never FALSE $Count = 1;

while ($Count <= 10) {

}

5

The while Structure

• PHP supports the C style while loop

– The body of the cycle will be executed until the condition is met

– The body consists of one or more statements

• If more than one, surrounding braces are required

– The condition expression is of type boolean

$a = 1;

while ($a < 100) {

$a ++;

echo $a;

}// this will output

expression

body

6

2 3 4 … 99

Do .. While Loop

• Test the condition after executing a series of statements then repeats the execution as long as a given conditional expression evaluates to TRUE

• The syntax for the do...while statement is: do {

statement(s);

} while (conditional expression);

7

Do .. While Cont’d

• do...while statements always execute

once, before a conditional expression is evaluated

$Count = 2;

do {

echo " <p>The count is equal to

$Count</p> ";

$Count++;

} while ($Count < 2);

8

do… while Structure

• The do-while structure is similar to while-do

– The condition is checked after the body is executed!

– The body is executed at least once!

$a = 1;

do {

$a ++;

echo $a;

} while ($a < 100);

//this will produce

//the previous while cycle’s output was: 2 3 4 … 99

expression

body

9

2 3 4 … 100

For Loop

• Combine the initialize, conditional evaluation, and update portions of a loop into a single statement.

• Repeat a statement or a series of statements as long as a given conditional expression evaluates to TRUE.

• If the conditional expression evaluates to TRUE, the for statement executes and continues to execute repeatedly until the conditional expression evaluates to FALSE.

10

for Cycle

• PHP supports C style for cycles

– The for cycle requires initialization, iteration and

ending condition statement • None of them are obligatory • Each statement can consist of multiple comma

separated statements

for ($i = 0; $i < 10; $i++)

echo $i;

for ($i = 0, $j = 10; ; $i++, $j--)

if ($j > $i)

echo $i;

else break;

body

initialization end condition iteration

11

break and continue

• You can leave a cycle with the break command

• You can move immediately to next cycle iteration with continue command

$i = 0;

while (true) {

$i ++;

if ($i == 10) break; // exit the cycle

if ($i%2 == 0) continue; // next iteration

echo $i;

}

12

$i = 0;

while ($i < 10) {

if ($i%2 == 1)

echo $i;

$i ++;

}

for ($i = 1; $i < 10; $i+2)

echo $i;

will print out 1 3 5 7 9

Exercise #3

• Using PHP loops, make this HTML table.

13

<td style='background-color:red'>

<td style='background-color:red'>

width = '50'

Colorful_list.php

Outline

• PHP Loops

• PHPMyAdmin

• Introducing SQL

• Connecting Database from PHP

• Exercises

14

From, Tools

phpMyAdmin, we can

manage MySQL

15

What is phpMyAdmin?

• PhpMyAdmin is a Web-based front end for managing mySQL databases.

• It has GUI screen for many common functions in mySQL.

• Makes mySQL more user friendly.

About phpMyAdmin

• Project started in 1998

• Uses GNU General Public License

• Platform independent

• http://www.phpmyadmin.net

What can phpMyAdmin do?

• Create and drop databases and tables.

• Work with multiple MySQL servers.

• Manage users and privileges.

• Export table data.

• Execute any SQL statement.

• 42 different languages.

• And more.

Create Database

19

Create Table

20

Table Specs

21

Table Created

22

Outline

• PHP Loops

• PHPMyAdmin

• Introducing SQL

• Connecting Database from PHP

• Exercises

23

Introducing SQL (Structured Query Language)

• SQL is a data definition language (DDL)

• CREATE DATABASE `CISC492`

• CREATE TABLE ‘Students’(

Student_Number varchar(10),

First_Name varchar(20),

Last_Name varchar(20),

Email varchar(30),

Mark FLOAT)

• DROP TABLE ’Students’

• DROP DATABASE ’CISC492’

Why not INT?

Introducing SQL

• SQL is also a data manipulation language (DML)

• INSERT INTO Students

VALUES (`05771234`, `Test`, `Example`,

`[email protected]`, `89`)

• SELECT * FROM Students

WHERE `Mark` BETWEEN 85 and 95

ORDER BY `Mark` DESC

• UPDATE Students SET Email = ‘[email protected]

WHERE Student_Number = ‘05771234’

• DELETE FROM Students

WHERE `Student_Number` = ‘05771234’

Outline

• PHP Loops

• PHPMyAdmin

• Introducing SQL

• Connecting Database from PHP

• Exercises

26

Connecting Database from PHP

1) Connecting MySQL

2) Sending & Executing Query

3) Fetching Data

27

1) Connecting MySQL • mysql_connect – function to connect to MySQL

server

– Returns database link identifier if successful

• mysql_select_db – function to select a particular

database from MySQL server

– Returns TRUE if successful

28

$dblink = mysql_connect("local

host", "root", "rootpass");

mysql_select_db("mydb", $dblink);

Password

Database link

identifier

Server name

or IP Address Username

2) Sending & Executing Query • mysql_query ($query, $dblink) – executes query

on database.

– $query is string – the query to be executed

– $dblink is the “database link identifier” previously returned from mysql_connect

• The returned result depends on the query

– If query is select, it returns a resource (result set) on successful or false on error.

– If query is insert, update, delete, it returns true on successful or false on error.

• The link parameter $dblink can be omitted if working with only one database throughout the script.

29

mysql_query("select * from students", $dblink);

3) Fetching Data

• mysql_fetch_assoc – returns associative

array containing the current row in result

and moved the pointer to the next one

– The field names are keys in the array

– Returns false if no more rows

30

$result = mysql_query("select * from students")

or die(mysql_error());

while ( $row = mysql_fetch_assoc($result) )

echo "Student Number: ".$row['Student_Number'].

" Student Mark: ".$row['Mark']."<br/>";

On error, display

error message

Assignment, not

comparison,

operator

Inserting Data & Number of Rows

31

$result = mysql_query (“INSERT INTO Students

VALUES (`05771234`, `Test`, `Example`,

`[email protected]`, `89`”) or die(mysql_error());

• mysql_num_rows ($result) –

returns the number of rows in a result set

$result = mysql_query ("select * from

students");

$count = mysql_num_rows($result);

echo “Total Number of Students is: $count”;

Exercise #3

32

Ex1_Insert.html

Insert.php

Exercise #4

33

Ex1_Insert.html

Show_Students.php

<td style='background-color:cyan'>

<th style='background-color:yellow'>

<tr style='background-color:orange'>

Descending Order

Functions (MySQL)

Category Example of functions

Aggregate MySQL: SUM, AVG, MAX, MIN, COUNT

Mathematical MySQL: SIN, COS, TAN, TRUNCATE, ROUND

Text MySQL: LEFT, RIGHT, SUBSTRING, LENGTH, LOWER, UPPER, LOCATE, REPLACE

Logical MySQL: IF, IFNULL

Conversion MySQL: FORMAT, CONVERT, DATEF_ORMAT, STR_TO_DATE

Date MySQL: CURDATE, DATEFORMAT, DAYOFMONTH, DAYOFWEEK, DAYNAME, MONTH, MONTHNAME, DATEDIFF, DATE_SUB

Time MySQL: CURTIME, HOUR, MINUTE, SECOND, TIMEDIFF

Functions (PHP)

Category Example of functions

Aggregate

Mathematical PHP: Sin, Cos, Tan, Floor, Round

Text PHP: SubStr, StrLen, StrToUpper, StrToLower, StrPos, SubStr_Replace

Logical PHP: If, While, For, Foreach, Switch

Conversion PHP: StrToTime

Date PHP: GetDate, Date

Time PHP: GetTimeOfDay, StrFTime

36