SlideShare a Scribd company logo
MySQL and PHP
Road Map
 MySQL Functions
 Connect to The Database
 Query the database
 Display table data
 Select individual records
2
MySQL Functions
mysql_connect
mysql_select_db
mysql_query
mysql_fetch_array
mysql_fetch_assoc
mysql_num_rows
mysql_close
Mysql_error
3
mysql_connect
You can connect to a MySQL database by using the mysql_connect
function.
A typical mysql_connect statement may look like the following:
$db = mysql_connect(ā€œlocalhostā€,
ā€œrootā€, ā€œpasswordā€);
4
mysql_select_db
The mysql_connect function returns a
database link identifier $db and its used
as an argument to the other MySQL
functions.
Selecting the database is a separate step
after you are connected to a MySQL
server; to do it, you use the
mysql_select_db function.
mysql_select_db(ā€œmydbā€, $db);
5
mysql_close
When you are finished using MySQL in a script, you close the
connection and free up its resources by using mysql_close, like this:
mysql_close($db);
6
mysql_query
The function to pass a SQL statement to MySQL is
mysql_query.
It takes two arguments the query itself and an
optional link identifier.
The following code executes a CREATE TABLE SQL
statement on the MySQL database for $db:
$sql = ā€œCREATE TABLE mytable (col1
INT, col2 VARCHAR(10))ā€;
mysql_query($sql, $db);
7
mysql_fetch_array
PHP provides a convenient way to work with more than one item
from a selected row of data at a time.
By using mysql_fetch_array, you can create
An array from the query result that contains one element for each
column in the query.
8
mysql_fetch_array
$sql = ā€œSELECT col1, col2 FROM
mytableā€;
$res = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($res))
{
echo ā€œcol1 =ā€œ.$row[ā€œcol1ā€];
echo ā€œcol2 =ā€œ.$row[ā€œcol2ā€].ā€œ<br>ā€;
}
Each row of data is fetched in turn, and in each
pass of the loop, the entire row of data is available
in the array structure
9
mysql_fetch_assoc
mysql_fetch_assoc
Which also returns the row as an associative
array.
mysql_num_rows
The function mysql_num_rows returns the
number of rows found by the query, and you
can use this value to create a loop with
mysql_result to examine every row in the
result.
10
mysql_num_rows
$sql = ā€œSELECT col1, col2 FROM mytableā€;
$res = mysql_query($sql, $db);
for ($i=0; $i < mysql_num_rows($res); $i++) {
echo ā€œcol1 = ā€œ . mysql_result($res, $i, 0);
echo ā€œ, col2 = ā€œ . mysql_result($res, $i, 1) .
ā€œ<br>ā€;
}
With the query used in this example,
because the column positions of col1 and
col2 are known, you can use mysql_result
with a numeric argument to specify each
one in turn.
11
Fetching Full Rows of Data
You can build a very powerful loop structure by
using mysql_fetch_array
$sql = ā€œSELECT col1, col2 FROM mytableā€;
$res = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($res)) {
echo ā€œcol1 = ā€œ . $row[ā€œcol1ā€];
echo ā€œ, col2 = ā€œ . $row[ā€œcol2ā€] . ā€œ<br>ā€;
}
Each row of data is fetched in turn, and in each pass of
the loop, the entire row of data is available in the array
structure
12
SQL Errors
When there is an error in a SQL statement,
it is not reported right away.
You should check the return value from
mysql_query to determine whether there
was a problem it is NULL if the query has
failed for any reason.
13
SQL Errors
The following example tries to perform an
invalid SQL statement (the table name is
missing from the DELETE command):
$sql = ā€œDELETE FROMā€;
$res = mysql_query($sql, $db);
if (!$res) {
echo ā€œThere was an SQL errorā€;
exit;
}
14
SQL Errors
If you want to find out why a call to
mysql_query failed, you must use the
mysql_error and mysql_errno functions to
retrieve the underlying MySQL warning text
and error code number.
if (!$res) {
echo ā€œError ā€œ . mysql_errno() . ā€œ in SQL ā€œ;
echo ā€œ<PRE>$sql</PRE>ā€;
echo mysql_error();
exit;
}
15
Connecting to Database
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the server
$dbhandle = mysql_connect($hostname,
$username, $password) or die("Unable to
connect to MySQL");
echo "Connected to MySQL";
16
Connecting to Database
//select a database to work with
$selected = mysql_select_db(ā€œpet",
$dbhandle) or die("Could not select
examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM
cars");
17
Select data in a table
//fetch tha data from the table
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row['idā€˜]." Name:".
$row['modelā€˜]."Year: ". //display the results
$row['yearā€˜]."<br>";
}
//close the connection
mysql_close($dbhandle);
18
Try out
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){die('Could not connect: ' . mysql_error());}
$sql = 'SELECT * FROM pet';
mysql_select_db(ā€˜webdb');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
19
Try out
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ".
"Submission Date : {$row['submission_date']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfullyn";
mysql_close($conn);
?>
20

More Related Content

PDF
Mysql & Php
PPTX
Php verses my sql
PDF
Php verses MySQL
PPTX
Database Connectivity in PHP
PDF
Using php with my sql
PDF
Introduction to php database connectivity
PPTX
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
PDF
Dependency Injection
Mysql & Php
Php verses my sql
Php verses MySQL
Database Connectivity in PHP
Using php with my sql
Introduction to php database connectivity
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Dependency Injection

What's hot (18)

PDF
CakeFest 2013 keynote
DOCX
Connectivity coding for java and mysql
PPTX
Learn PHP Lacture2
PDF
Agile database access with CakePHP 3
PPTX
Анатолий ŠŸŠ¾Š»ŃŠŗŠ¾Š² - Drupal.ajax framework from a to z
PPTX
MySql:Basics
PDF
Stored Procedure
PDF
äøŽ PHP 和 Perl 使用 MySQL ę•°ę®åŗ“
PPT
MySQL
PPTX
Beginner guide to mysql command line
PPTX
MySql:Introduction
PDF
MySQL for beginners
PDF
Sqlite perl
PDF
Internationalizing CakePHP Applications
DOCX
Transaction isolationexamples
PDF
Riak Search 2: Yokozuna
PDF
Web app development_crud_13
DOCX
Lock basicsexamples
CakeFest 2013 keynote
Connectivity coding for java and mysql
Learn PHP Lacture2
Agile database access with CakePHP 3
Анатолий ŠŸŠ¾Š»ŃŠŗŠ¾Š² - Drupal.ajax framework from a to z
MySql:Basics
Stored Procedure
äøŽ PHP 和 Perl 使用 MySQL ę•°ę®åŗ“
MySQL
Beginner guide to mysql command line
MySql:Introduction
MySQL for beginners
Sqlite perl
Internationalizing CakePHP Applications
Transaction isolationexamples
Riak Search 2: Yokozuna
Web app development_crud_13
Lock basicsexamples
Ad

Similar to Lecture6 display data by okello erick (20)

PPT
Php with MYSQL Database
PDF
PHP and Mysql
PPT
PHP - Getting good with MySQL part II
PDF
PHP with MySQL
PDF
Php verses MySQL
PPT
Synapse india reviews on php and sql
PPTX
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
PPTX
chapter_Seven Database manipulation using php.pptx
Ā 
PPTX
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT V (5).pptx
PPTX
lecture 7 - Introduction to MySQL with PHP.pptx
PDF
All Things Open 2016 -- Database Programming for Newbies
DOCX
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
PPTX
Php mysq
DOCX
Collection of built in functions for manipulating MySQL databases.docx
PPT
9780538745840 ppt ch08
PDF
4.3 MySQL + PHP
PDF
A Brief Introduction About Sql Injection in PHP and MYSQL
PPT
MYSQL - PHP Database Connectivity
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Php with MYSQL Database
PHP and Mysql
PHP - Getting good with MySQL part II
PHP with MySQL
Php verses MySQL
Synapse india reviews on php and sql
7. PHP and gaghhgashgfsgajhfkhshfasMySQL.pptx
chapter_Seven Database manipulation using php.pptx
Ā 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT V (5).pptx
lecture 7 - Introduction to MySQL with PHP.pptx
All Things Open 2016 -- Database Programming for Newbies
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Php mysq
Collection of built in functions for manipulating MySQL databases.docx
9780538745840 ppt ch08
4.3 MySQL + PHP
A Brief Introduction About Sql Injection in PHP and MYSQL
MYSQL - PHP Database Connectivity
Pyhton with Mysql to perform CRUD operations.pptx
Ad

More from okelloerick (11)

PPT
My sql statements by okello erick
PPT
Lecture8 php page control by okello erick
PPT
Lecture7 form processing by okello erick
PPTX
Lecture5 my sql statements by okello erick
PPTX
Lecture4 php by okello erick
PPTX
Lecture3 php by okello erick
PPTX
Lecture3 mysql gui by okello erick
PPTX
Lecture2 mysql by okello erick
PPTX
Lecture1 introduction by okello erick
PPT
Data commn intro by okello erick
PPT
Computer networks--networking hardware
My sql statements by okello erick
Lecture8 php page control by okello erick
Lecture7 form processing by okello erick
Lecture5 my sql statements by okello erick
Lecture4 php by okello erick
Lecture3 php by okello erick
Lecture3 mysql gui by okello erick
Lecture2 mysql by okello erick
Lecture1 introduction by okello erick
Data commn intro by okello erick
Computer networks--networking hardware

Recently uploaded (20)

PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
Doc9.....................................
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
PPTX
How Much Does It Cost to Build a Train Ticket App like Trenitalia in Italy.pptx
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Ā 
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
PDF
Software Development Methodologies in 2025
Ā 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
PDF
DevOps & Developer Experience Summer BBQ
Ā 
Reimagining Insurance: Connected Data for Confident Decisions.pdf
A Day in the Life of Location Data - Turning Where into How.pdf
Doc9.....................................
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
ChatGPT's Deck on The Enduring Legacy of Fax Machines
How Much Does It Cost to Build a Train Ticket App like Trenitalia in Italy.pptx
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Event Presentation Google Cloud Next Extended 2025
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
GamePlan Trading System Review: Professional Trader's Honest Take
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Ā 
Top Generative AI Tools for Patent Drafting in 2025.pdf
CroxyProxy Instagram Access id login.pptx
Enable Enterprise-Ready Security on IBM i Systems.pdf
Software Development Methodologies in 2025
Ā 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
agentic-ai-and-the-future-of-autonomous-systems.pdf
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
DevOps & Developer Experience Summer BBQ
Ā 

Lecture6 display data by okello erick

  • 2. Road Map  MySQL Functions  Connect to The Database  Query the database  Display table data  Select individual records 2
  • 4. mysql_connect You can connect to a MySQL database by using the mysql_connect function. A typical mysql_connect statement may look like the following: $db = mysql_connect(ā€œlocalhostā€, ā€œrootā€, ā€œpasswordā€); 4
  • 5. mysql_select_db The mysql_connect function returns a database link identifier $db and its used as an argument to the other MySQL functions. Selecting the database is a separate step after you are connected to a MySQL server; to do it, you use the mysql_select_db function. mysql_select_db(ā€œmydbā€, $db); 5
  • 6. mysql_close When you are finished using MySQL in a script, you close the connection and free up its resources by using mysql_close, like this: mysql_close($db); 6
  • 7. mysql_query The function to pass a SQL statement to MySQL is mysql_query. It takes two arguments the query itself and an optional link identifier. The following code executes a CREATE TABLE SQL statement on the MySQL database for $db: $sql = ā€œCREATE TABLE mytable (col1 INT, col2 VARCHAR(10))ā€; mysql_query($sql, $db); 7
  • 8. mysql_fetch_array PHP provides a convenient way to work with more than one item from a selected row of data at a time. By using mysql_fetch_array, you can create An array from the query result that contains one element for each column in the query. 8
  • 9. mysql_fetch_array $sql = ā€œSELECT col1, col2 FROM mytableā€; $res = mysql_query($sql, $conn); while ($row = mysql_fetch_array($res)) { echo ā€œcol1 =ā€œ.$row[ā€œcol1ā€]; echo ā€œcol2 =ā€œ.$row[ā€œcol2ā€].ā€œ<br>ā€; } Each row of data is fetched in turn, and in each pass of the loop, the entire row of data is available in the array structure 9
  • 10. mysql_fetch_assoc mysql_fetch_assoc Which also returns the row as an associative array. mysql_num_rows The function mysql_num_rows returns the number of rows found by the query, and you can use this value to create a loop with mysql_result to examine every row in the result. 10
  • 11. mysql_num_rows $sql = ā€œSELECT col1, col2 FROM mytableā€; $res = mysql_query($sql, $db); for ($i=0; $i < mysql_num_rows($res); $i++) { echo ā€œcol1 = ā€œ . mysql_result($res, $i, 0); echo ā€œ, col2 = ā€œ . mysql_result($res, $i, 1) . ā€œ<br>ā€; } With the query used in this example, because the column positions of col1 and col2 are known, you can use mysql_result with a numeric argument to specify each one in turn. 11
  • 12. Fetching Full Rows of Data You can build a very powerful loop structure by using mysql_fetch_array $sql = ā€œSELECT col1, col2 FROM mytableā€; $res = mysql_query($sql, $conn); while ($row = mysql_fetch_array($res)) { echo ā€œcol1 = ā€œ . $row[ā€œcol1ā€]; echo ā€œ, col2 = ā€œ . $row[ā€œcol2ā€] . ā€œ<br>ā€; } Each row of data is fetched in turn, and in each pass of the loop, the entire row of data is available in the array structure 12
  • 13. SQL Errors When there is an error in a SQL statement, it is not reported right away. You should check the return value from mysql_query to determine whether there was a problem it is NULL if the query has failed for any reason. 13
  • 14. SQL Errors The following example tries to perform an invalid SQL statement (the table name is missing from the DELETE command): $sql = ā€œDELETE FROMā€; $res = mysql_query($sql, $db); if (!$res) { echo ā€œThere was an SQL errorā€; exit; } 14
  • 15. SQL Errors If you want to find out why a call to mysql_query failed, you must use the mysql_error and mysql_errno functions to retrieve the underlying MySQL warning text and error code number. if (!$res) { echo ā€œError ā€œ . mysql_errno() . ā€œ in SQL ā€œ; echo ā€œ<PRE>$sql</PRE>ā€; echo mysql_error(); exit; } 15
  • 16. Connecting to Database $username = "your_name"; $password = "your_password"; $hostname = "localhost"; //connection to the server $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); echo "Connected to MySQL"; 16
  • 17. Connecting to Database //select a database to work with $selected = mysql_select_db(ā€œpet", $dbhandle) or die("Could not select examples"); //execute the SQL query and return records $result = mysql_query("SELECT * FROM cars"); 17
  • 18. Select data in a table //fetch tha data from the table while ($row = mysql_fetch_array($result)) { echo "ID:".$row['idā€˜]." Name:". $row['modelā€˜]."Year: ". //display the results $row['yearā€˜]."<br>"; } //close the connection mysql_close($dbhandle); 18
  • 19. Try out <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ){die('Could not connect: ' . mysql_error());} $sql = 'SELECT * FROM pet'; mysql_select_db(ā€˜webdb'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } 19
  • 20. Try out if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']} <br> ". "Author: {$row['tutorial_author']} <br> ". "Submission Date : {$row['submission_date']} <br> ". "--------------------------------<br>"; } echo "Fetched data successfullyn"; mysql_close($conn); ?> 20