SlideShare une entreprise Scribd logo
1  sur  25
1
Internet Programming
Connecting PHP to a
Database
2
Objectives
To construct programs that interact with
MySQL database.
TAB1033 - Internet Programming 3
How they are connected?
4
MySQL
A Relational Database with a license,
allowing users to use it cost-free for
most non-commercial purposes.
A database choice for PHP developers.
Conceived as fast and flexible DBMS.
5
Getting a Connection
Connect to any server that have permission to
use.
The mysql_connect function arranges the
communication link between MySQL and PHP.
The mysql_connect() function requires
three parameters:
 Server name : name or URL of the MySQL server
 Username : The username in MySql.
 Password : password identified by username
6
Steps for Accessing MySQL
Database
1.Open a connection to MySQL
2.Select a particular database
$connection = mysql_connect(host,username, password);
$db = mysql_select_db( database_name , $connection );
$connection = mysql_connect("160.0.58.165", "stud0011",
"iiiiiiii");
$db = mysql_select_db("test" , $connection );
7
Steps for Accessing MySQL
Database (cont.)
3. Access the tables in the database as
required
a. Create an SQL command string
containing your query.
$sql = "sql_command parameters";
$sql = "SELECT * FROM contact";
8
Steps for Accessing MySQL
Database (cont.)
b. Execute the query
c. Deal with the result of the query
$result = mysql_query( $sql , $connection ) or
die("Couldn't execute query");
while($row = mysql_fetch_array($result)){ ... }
"SELECT * FROM contact";
9
Creating an SQL Table
A bit tedious process
Easier if you could use phpMyAdmin
CREATE TABLE table_name
(
fieldname1 data_type(size);
fieldname2 data_type(size);
fieldname3 data_type(size);
.
.
.
fieldname-n data_type(size);
);
10
SQL Commands
The main day-to-day queries used from
PHP scripts:
 INSERT INTO tablename ... VALUES ... ;
 REPLACE INTO tablename ... VALUES ... ;
 DELETE FROM tablename WHERE ... ;
 UPDATE tablename SET ... WHERE ... ;
 SELECT ... FROM tablename WHERE ...
ORDER BY... ;
11
SQL Commands (cont.)
When writing SQL commands into PHP
scripts the usual problem of too many
quotes arises and 'internal' quotes (")
have to be escaped.
SQL query must finish with a semicolon,
as must a PHP script command.
12
Examples of Built-In MySQL
Functions
 Returns an array that represents all the fields for a
row in the result set.
 Eg. $row = mysql_fetch_row($result)
 Moves the internal row pointer of a result to the
specified row, with rows counting from zero.
 Use this function with mysql_fetch_row to jump
to a specific row.
 Eg. $row = mysql_data_seek($result, 3)
array mysql_fetch_row(resource result)
boolean mysql_data_seek(resource result, integer row)
13
Built-In MySQL Functions
array mysql_fetch_array(resource result,integer type)
Returns an array that represents all the fields for a row in the
result set.
Value is stored twice: Once indexed by offset starting from
zero, once indexed by the name of the field.
Eg. $row = mysql_fetch_array($result, 5)
array mysql_fetch_assoc(resource result)
Returns an array that represents all the fields for a row in the
result set.
Element is indexed by the names of the field only
Eg. $row = mysql_fetch_assoc($result)
14
Examples
To create a web page that linked to sale
items record from a database.
Step 1: Create the table named catalog
in a database
CREATE TABLE catalog
(
ID INT(11) NOT NULL AUTO_INCREMENT,
Name CHAR(32),
Price DECIMAL(6,2),
PRIMARY KEY (ID)
);
15
Example
Step 2 : Insert some items along with some
dummy prices.
INSERT INTO catalog (Name, Price) VALUES
(' Shampoo ' , 6.50),
(' Brush ', 2.00),
(' Conditioner ', 7.00),
(' Toothbrush ', 3.50),
(' Dental Floss ', 5.00);
SELECT * FROM catalog
16
Example
Step 3: Write a PHP script to retrieve the data
from table and display them in HTML table
<?php
//connect to server, then test for failure
if(!($dbLink = mysql_connect(" localhost ", " user1", "")))
{
print("Failed to connect to database!<br>n");
print("Aborting!<br>n");
exit();
}
//select database then test for failure
if (!($dbResult = mysql_query("USE test", $dbLink)))
{
print("Cannot use the test database!<br>n");
print("Aborting!<br>n");
exit();
}
Database connection
No password
query
17
Example
Creating HTML table from a query (cont.)
//get eveything from catalog table
$Query = "SELECT Name, Price " .
"FROM catalog " .
"ORDER BY Name ";
if(!($dbResult = mysql_query($Query, $dbLink)))
{
print("Could not execute query!<br>n");
print("MySQL reports: " . mysql_error() . !<br>n");
print("Query was: $Query<br>n");
exit();
}
TAB1033 - Internet Programming 18
Example
Creating HTML table from a query (cont.)
//start table
print("<table border = "0 ">n");
//create header row
print("<tr>n");
print("<td><b>Item</b></td>n");
print("<td><b>Price</b></td>n");
print("</tr>n");
//get each row
while ($dbRow = mysql_fetch_assoc($dbResult))
{
print("<tr>n");
print("<td>{$dbRow['Name']}</td>n");
print("<td align=right">{$dbRow['Price']}</td>n");
print("</tr>n");
}
//end table
print("</table>n");
?>
Fetch each row from the result set.
Expresses each column in the
result as an element of an
associative array.
Field name
19
Output
20
Drop Table
DROP TABLE IF EXIST catalog;
21
Changing Data With the Update
Statement
UPDATE catalog
SET price = 10.00
WHERE name = 'Shampoo';
UPDATE table_name
SET fieldname1 = value
WHERE fieldname2 = value;
22
Delete Data?
DELETE FROM catalog
WHERE name = 'Shampoo' AND price < 7.00 ;
DELETE FROM table_name WHERE fieldname2 = value;
23
Summary
Database Connection
 For example:
 Host: 160.0.58.165
 Username:stud9988
 Password: mypass123
 Database Name : db9988
 Connection
$connection = mysql_connect("160.0.58.165",
"stud9988", "mypass123");
24
Summary
Select database
$db = mysql_select_db("db9988" , $connection );
Select data from table student in database
db9988
$query = "SELECT id, name FROM student
WHERE id = ‘1234'";
$result = mysql_query($query,$connection)
or die("Couldn't execute query");
The result (output)
while($row = mysql_fetch_row($result)){
print($row[0]);//1234
print($row[1]);//Ali
}
id name
1234 Ali
6789 Mary
student
25
Summary
Update data
$query1 = "UPDATE student SET name = 'Ahmad'
WHERE id = 1234";
• Delete data
$query2 = "DELETE FROM student WHERE name =
'Mary'";
Drop table
$query3 = "DROP TABLE IF EXIST student;";
id name
1234 Ali
6789 Mary
student

Contenu connexe

Tendances

Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 

Tendances (17)

Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Mysql
MysqlMysql
Mysql
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Cake PHP 3 Presentaion
Cake PHP 3 PresentaionCake PHP 3 Presentaion
Cake PHP 3 Presentaion
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
System performance tuning
System performance tuningSystem performance tuning
System performance tuning
 
PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014PDO Basics - PHPMelb 2014
PDO Basics - PHPMelb 2014
 
Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivity
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Php and database functionality
Php and database functionalityPhp and database functionality
Php and database functionality
 
Php summary
Php summaryPhp summary
Php summary
 
lab56_db
lab56_dblab56_db
lab56_db
 

En vedette (10)

American psychological association (apa)
American psychological association (apa)American psychological association (apa)
American psychological association (apa)
 
The Basics of APA Style, 6th Edition
The Basics of APA Style, 6th EditionThe Basics of APA Style, 6th Edition
The Basics of APA Style, 6th Edition
 
Apa citation style 6th edition
Apa citation style 6th editionApa citation style 6th edition
Apa citation style 6th edition
 
APA 6th edition
APA 6th editionAPA 6th edition
APA 6th edition
 
APA Style Citation (6th edition) Guide 2.0
APA Style Citation (6th edition) Guide 2.0APA Style Citation (6th edition) Guide 2.0
APA Style Citation (6th edition) Guide 2.0
 
Apa format 6th edition
Apa format 6th editionApa format 6th edition
Apa format 6th edition
 
Apa 6th edition publication manual
Apa 6th edition publication manualApa 6th edition publication manual
Apa 6th edition publication manual
 
APA referencing style
APA referencing styleAPA referencing style
APA referencing style
 
Rule Based Architecture System
Rule Based Architecture SystemRule Based Architecture System
Rule Based Architecture System
 
Social Psychology PowerPoint
Social Psychology PowerPointSocial Psychology PowerPoint
Social Psychology PowerPoint
 

Similaire à PHP - Getting good with MySQL part II

Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08
Terry Yoast
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
moirarandell
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 

Similaire à PHP - Getting good with MySQL part II (20)

Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08
 
Php mysq
Php mysqPhp mysq
Php mysq
 
Python database access
Python database accessPython database access
Python database access
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptx
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
 
Php 2
Php 2Php 2
Php 2
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7
 
Php Mysql
Php Mysql Php Mysql
Php Mysql
 

Plus de Firdaus Adib

Final Paper UTP Algorithm Data Structure January 2010
Final Paper UTP Algorithm Data Structure January 2010Final Paper UTP Algorithm Data Structure January 2010
Final Paper UTP Algorithm Data Structure January 2010
Firdaus Adib
 
Additional exercise for apa references
Additional exercise for apa referencesAdditional exercise for apa references
Additional exercise for apa references
Firdaus Adib
 

Plus de Firdaus Adib (19)

Wireless Technology Proj spec
Wireless Technology Proj spec Wireless Technology Proj spec
Wireless Technology Proj spec
 
Corporate Ethics January 2010
Corporate Ethics January 2010Corporate Ethics January 2010
Corporate Ethics January 2010
 
Corporate Ethics July 2008
Corporate Ethics July 2008Corporate Ethics July 2008
Corporate Ethics July 2008
 
Final Paper UTP Web Development Application July 2008
Final Paper UTP Web Development Application July 2008Final Paper UTP Web Development Application July 2008
Final Paper UTP Web Development Application July 2008
 
Final Paper UTP Algorithm Data Structure July 2008
Final Paper UTP Algorithm Data Structure July 2008Final Paper UTP Algorithm Data Structure July 2008
Final Paper UTP Algorithm Data Structure July 2008
 
Final Paper UTP Web Development Application January 2010
Final Paper UTP Web Development Application January 2010Final Paper UTP Web Development Application January 2010
Final Paper UTP Web Development Application January 2010
 
Final Paper UTP Algorithm Data Structure January 2010
Final Paper UTP Algorithm Data Structure January 2010Final Paper UTP Algorithm Data Structure January 2010
Final Paper UTP Algorithm Data Structure January 2010
 
Final Paper UTP Web Development Application July 2009
Final Paper UTP Web Development Application July 2009Final Paper UTP Web Development Application July 2009
Final Paper UTP Web Development Application July 2009
 
PHP - Getting good with MySQL part I
PHP - Getting good with MySQL part IPHP - Getting good with MySQL part I
PHP - Getting good with MySQL part I
 
Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with session
 
PHP - Getting good with cookies
PHP - Getting good with cookiesPHP - Getting good with cookies
PHP - Getting good with cookies
 
Javascript - Getting Good with Object
Javascript - Getting Good with ObjectJavascript - Getting Good with Object
Javascript - Getting Good with Object
 
Javascript - Getting Good with Loop and Array
Javascript - Getting Good with Loop and ArrayJavascript - Getting Good with Loop and Array
Javascript - Getting Good with Loop and Array
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Additional exercise for apa references
Additional exercise for apa referencesAdditional exercise for apa references
Additional exercise for apa references
 
Chapter 2 summarising
Chapter 2 summarisingChapter 2 summarising
Chapter 2 summarising
 
Referencing and Citing
Referencing and CitingReferencing and Citing
Referencing and Citing
 
Chapter 2 paraphrasing
Chapter 2 paraphrasingChapter 2 paraphrasing
Chapter 2 paraphrasing
 
Introduction to oil & gas [read only]
Introduction to oil & gas [read only]Introduction to oil & gas [read only]
Introduction to oil & gas [read only]
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 

PHP - Getting good with MySQL part II

  • 2. 2 Objectives To construct programs that interact with MySQL database.
  • 3. TAB1033 - Internet Programming 3 How they are connected?
  • 4. 4 MySQL A Relational Database with a license, allowing users to use it cost-free for most non-commercial purposes. A database choice for PHP developers. Conceived as fast and flexible DBMS.
  • 5. 5 Getting a Connection Connect to any server that have permission to use. The mysql_connect function arranges the communication link between MySQL and PHP. The mysql_connect() function requires three parameters:  Server name : name or URL of the MySQL server  Username : The username in MySql.  Password : password identified by username
  • 6. 6 Steps for Accessing MySQL Database 1.Open a connection to MySQL 2.Select a particular database $connection = mysql_connect(host,username, password); $db = mysql_select_db( database_name , $connection ); $connection = mysql_connect("160.0.58.165", "stud0011", "iiiiiiii"); $db = mysql_select_db("test" , $connection );
  • 7. 7 Steps for Accessing MySQL Database (cont.) 3. Access the tables in the database as required a. Create an SQL command string containing your query. $sql = "sql_command parameters"; $sql = "SELECT * FROM contact";
  • 8. 8 Steps for Accessing MySQL Database (cont.) b. Execute the query c. Deal with the result of the query $result = mysql_query( $sql , $connection ) or die("Couldn't execute query"); while($row = mysql_fetch_array($result)){ ... } "SELECT * FROM contact";
  • 9. 9 Creating an SQL Table A bit tedious process Easier if you could use phpMyAdmin CREATE TABLE table_name ( fieldname1 data_type(size); fieldname2 data_type(size); fieldname3 data_type(size); . . . fieldname-n data_type(size); );
  • 10. 10 SQL Commands The main day-to-day queries used from PHP scripts:  INSERT INTO tablename ... VALUES ... ;  REPLACE INTO tablename ... VALUES ... ;  DELETE FROM tablename WHERE ... ;  UPDATE tablename SET ... WHERE ... ;  SELECT ... FROM tablename WHERE ... ORDER BY... ;
  • 11. 11 SQL Commands (cont.) When writing SQL commands into PHP scripts the usual problem of too many quotes arises and 'internal' quotes (") have to be escaped. SQL query must finish with a semicolon, as must a PHP script command.
  • 12. 12 Examples of Built-In MySQL Functions  Returns an array that represents all the fields for a row in the result set.  Eg. $row = mysql_fetch_row($result)  Moves the internal row pointer of a result to the specified row, with rows counting from zero.  Use this function with mysql_fetch_row to jump to a specific row.  Eg. $row = mysql_data_seek($result, 3) array mysql_fetch_row(resource result) boolean mysql_data_seek(resource result, integer row)
  • 13. 13 Built-In MySQL Functions array mysql_fetch_array(resource result,integer type) Returns an array that represents all the fields for a row in the result set. Value is stored twice: Once indexed by offset starting from zero, once indexed by the name of the field. Eg. $row = mysql_fetch_array($result, 5) array mysql_fetch_assoc(resource result) Returns an array that represents all the fields for a row in the result set. Element is indexed by the names of the field only Eg. $row = mysql_fetch_assoc($result)
  • 14. 14 Examples To create a web page that linked to sale items record from a database. Step 1: Create the table named catalog in a database CREATE TABLE catalog ( ID INT(11) NOT NULL AUTO_INCREMENT, Name CHAR(32), Price DECIMAL(6,2), PRIMARY KEY (ID) );
  • 15. 15 Example Step 2 : Insert some items along with some dummy prices. INSERT INTO catalog (Name, Price) VALUES (' Shampoo ' , 6.50), (' Brush ', 2.00), (' Conditioner ', 7.00), (' Toothbrush ', 3.50), (' Dental Floss ', 5.00); SELECT * FROM catalog
  • 16. 16 Example Step 3: Write a PHP script to retrieve the data from table and display them in HTML table <?php //connect to server, then test for failure if(!($dbLink = mysql_connect(" localhost ", " user1", ""))) { print("Failed to connect to database!<br>n"); print("Aborting!<br>n"); exit(); } //select database then test for failure if (!($dbResult = mysql_query("USE test", $dbLink))) { print("Cannot use the test database!<br>n"); print("Aborting!<br>n"); exit(); } Database connection No password query
  • 17. 17 Example Creating HTML table from a query (cont.) //get eveything from catalog table $Query = "SELECT Name, Price " . "FROM catalog " . "ORDER BY Name "; if(!($dbResult = mysql_query($Query, $dbLink))) { print("Could not execute query!<br>n"); print("MySQL reports: " . mysql_error() . !<br>n"); print("Query was: $Query<br>n"); exit(); }
  • 18. TAB1033 - Internet Programming 18 Example Creating HTML table from a query (cont.) //start table print("<table border = "0 ">n"); //create header row print("<tr>n"); print("<td><b>Item</b></td>n"); print("<td><b>Price</b></td>n"); print("</tr>n"); //get each row while ($dbRow = mysql_fetch_assoc($dbResult)) { print("<tr>n"); print("<td>{$dbRow['Name']}</td>n"); print("<td align=right">{$dbRow['Price']}</td>n"); print("</tr>n"); } //end table print("</table>n"); ?> Fetch each row from the result set. Expresses each column in the result as an element of an associative array. Field name
  • 20. 20 Drop Table DROP TABLE IF EXIST catalog;
  • 21. 21 Changing Data With the Update Statement UPDATE catalog SET price = 10.00 WHERE name = 'Shampoo'; UPDATE table_name SET fieldname1 = value WHERE fieldname2 = value;
  • 22. 22 Delete Data? DELETE FROM catalog WHERE name = 'Shampoo' AND price < 7.00 ; DELETE FROM table_name WHERE fieldname2 = value;
  • 23. 23 Summary Database Connection  For example:  Host: 160.0.58.165  Username:stud9988  Password: mypass123  Database Name : db9988  Connection $connection = mysql_connect("160.0.58.165", "stud9988", "mypass123");
  • 24. 24 Summary Select database $db = mysql_select_db("db9988" , $connection ); Select data from table student in database db9988 $query = "SELECT id, name FROM student WHERE id = ‘1234'"; $result = mysql_query($query,$connection) or die("Couldn't execute query"); The result (output) while($row = mysql_fetch_row($result)){ print($row[0]);//1234 print($row[1]);//Ali } id name 1234 Ali 6789 Mary student
  • 25. 25 Summary Update data $query1 = "UPDATE student SET name = 'Ahmad' WHERE id = 1234"; • Delete data $query2 = "DELETE FROM student WHERE name = 'Mary'"; Drop table $query3 = "DROP TABLE IF EXIST student;"; id name 1234 Ali 6789 Mary student

Notes de l'éditeur

  1. Packets contained data address, error control and sequencing information. TCP : ensure that messages were properly routed from sender to receiver IP : Creating “network of networks”. Get different networks to communicate
  2. RED LEVEL : Internet &amp;quot;Backbone&amp;quot;. It is the main highest-traffic network,interconnects the routers of the second level. Internet Routers — shown as round black &amp;quot;nodes&amp;quot; in this diagram — examine the destinations of individual Internet data packets,determine the best route to use in forwarding the data to its final destination. BLUE LEVEL : large &amp;quot;Tier-1&amp;quot; service providers. They purchase &amp;quot;backbone&amp;quot; bandwidth from the major communications carriers and resell it to smaller service providers, universities, and corporations. GREEN LEVEL : composed of smaller (non-Tier-1) service providers, universities, and corporations. Purchase bandwidth from Tier-1 providers and interconnect the individual machines within their organizations into a &amp;quot;Local Area Network&amp;quot; (LAN). BLACK LEVEL : composed of the connections to individual machines. This is often called the &amp;quot;Last Mile&amp;quot; of the Internet and ranges from dial-up modems, to ISDN, to DSL, to Cable Modem, to local Ethernet segments.
  3. Problem : interruption in the connection of two-tiered architecture could put the entire data transaction in risk of loss.