SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Chapter 8
Manipulating MySQL
Databases with PHP
PHP Programming with MySQL
2nd
Edition
2PHP Programming with MySQL, 2nd Edition
Objectives
In this chapter, you will:
• Connect to MySQL from PHP
• Work with MySQL databases using PHP
• Create, modify, and delete MySQL tables with
PHP
• Use PHP to manipulate MySQL records
• Use PHP to retrieve database records
3PHP Programming with MySQL, 2nd Edition
Connecting to MySQL with PHP
• PHP has the ability to access and manipulate
any database that is ODBC compliant
• PHP includes functionality that allows you to
work directly with different types of databases,
without going through ODBC
• PHP supports SQLite, database abstraction
layer functions, and PEAR DB
4PHP Programming with MySQL, 2nd Edition
Determining which MySQL
Package to Use
• The mysqli (MySQL Improved) package
became available with PHP 5 and is designed to
work with MySQL version 4.1.3 and later
• Earlier versions must use the mysql package
• The mysqli package is the object-oriented
equivalent of the mysql package
5PHP Programming with MySQL, 2nd Edition
Opening and Closing a MySQL
Connection
• Open a connection to a MySQL database server
with the mysql_connect() function
• The mysql_connect() function returns a
positive integer if it connects to the database
successfully or FALSE if it does not
• Assign the return value from the
mysql_connect() function to a variable that
you can use to access the database in your
script
6PHP Programming with MySQL, 2nd Edition
Opening and Closing a MySQL
Connection (continued)
• The syntax for the mysql_connect()
function is:
$connection = mysql_connect("host" [,
"user", "password"]);
• The host argument specifies the host name
where your MySQL database server is installed
• The user and password arguments specify a
MySQL account name and password
7PHP Programming with MySQL, 2nd Edition
Opening and Closing a MySQL
Connection (continued)
• The database connection is assigned to the
$DBConnect variable
$DBConnect = mysql_connect("localhost",
"dongosselin ", "rosebud");
•
Close a database connection using the
mysql_close() function
mysql_close($DBConnect);
8PHP Programming with MySQL, 2nd Edition
Opening and Closing a MySQL
Connection (continued)
9PHP Programming with MySQL, 2nd Edition
Opening and Closing a MySQL
Connection (continued)
Figure 8-1 MySQLInfo.php in a Web browser
10PHP Programming with MySQL, 2nd Edition
Reporting MySQL Errors
• Reasons for not connecting to a database server
include:
– The database server is not running
– Insufficient privileges to access the data source
– Invalid username and/or password
Reporting MySQL Errors
(continued)
• The mysql_errno() function returns the error
code from the last attempted MySQL function
call or 0 if no error occurred
• The mysql_errno() and mysql_error()
functions return the results of the previous
mysql*() function
11PHP Programming with MySQL, 2nd Edition
12PHP Programming with MySQL, 2nd Edition
Suppressing Errors with the Error
Control Operator
• By default, functions in the mysql package
display errors and warnings as they occur
• Use the error control operator (@) to suppress
error messages
• The error control operator can be prepended to
any expression although it is commonly used
with expressions
Creating a Database
• Use the mysql_create_db() function to
create a new database
• The basic syntax for the mysql_create_db()
is:
$result = mysql_create_db( "dbname" [,
connection]);
• The mysql_create_db() returns a Boolean
TRUE if successful or FALSE if there was an
error
13PHP Programming with MySQL, 2nd Edition
Creating a Database (continued)
Figure 8-2 Error message when the mysql_create_db()
function is unavailable because of insufficient privileges
14PHP Programming with MySQL, 2nd Edition
15PHP Programming with MySQL, 2nd Edition
Selecting a Database
• The syntax for the mysql_select_db()
function is:
mysql_select_db(database [,
connection]);
• The function returns a value of TRUE if it
successfully selects a database or FALSE if it
does not
• For security purposes, you may choose to use
an include file to connect to the MySQL server
and select a database
Deleting a Database
• To delete a database, use the
mysql_drop_db() function.
• The format for the mysql_drop_db() function
is:
$Result = mysql_drop_db("dbname" [,
connection]);
• The function returns a value of TRUE if it
successfully drops a database or FALSE if it
does not
16PHP Programming with MySQL, 2nd Edition
17PHP Programming with MySQL, 2nd Edition
Executing SQL Statements
• Use the mysql_query() function to send SQL
statements to MySQL
• The syntax for the mysql_query() function is:
mysql_query(query [, connection]);
• The mysql_query() function returns one of
three values:
– For SQL statements that do not return results
(CREATE DATABASE and CREATE TABLE
statements) it returns a value of TRUE if the
statement executes successfully
18PHP Programming with MySQL, 2nd Edition
Executing SQL Statements
(continued)
– For SQL statements that return results (SELECT
and SHOW statements) the mysql_query()
function returns a result pointer that represents
the query results
• A result pointer is a special type of variable that
refers to the currently selected row in a resultset
– The mysql_query() function returns a value of
FALSE for any SQL statements that fail,
regardless of whether they return results
Creating and Deleting Tables
• Use the CREATE TABLE statement with the
mysql_query() function to create a new table
• Use the mysql_select_db() function before
executing the CREATE TABLE statement to
verify that you are in the right database
19PHP Programming with MySQL, 2nd Edition
Creating and Deleting Tables
(continued)
$SQLstring = "CREATE TABLE drivers (name
VARCHAR(100), "
. "emp_no SMALLINT, hire_date DATE, "
. "stop_date DATE)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult===FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " .
mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) .
"</p>";
else
echo "<p>Successfully created the table.</p>";
20PHP Programming with MySQL, 2nd Edition
Creating and Deleting Tables
(continued)
Figure 8-3 Error code and message that displays when you
attempt to create a table that already exists
21PHP Programming with MySQL, 2nd Edition
22PHP Programming with MySQL, 2nd Edition
Creating and Deleting Tables
(continued)
• Use the SHOW TABLES LIKE command to
prevent code from trying to create a table that
already exists.
• If the table does not exist, the
mysql_num_rows()function will return a value
of 0 rows
$TableName = "subscribers";
$SQLstring = "SHOW TABLES LIKE '$TableName'";
$QueryResult = @mysql_query($SQLstring,
$DBConnect);
Creating and Deleting Tables
(continued)
• To identify a field as a primary key in MySQL,
include the PRIMARY KEY keywords when you
define a field with the CREATE TABLE
statement
• The AUTO_INCREMENT keyword is often used
with a primary key to generate a unique ID for
each new row in a table
• The NOT NULL keywords are often used with
primary keys to require that a field include a
value
23PHP Programming with MySQL, 2nd Edition
Creating and Deleting Tables
(continued)
• To delete a table, use the DROP TABLE
statement with the mysql_query() function
24PHP Programming with MySQL, 2nd Edition
Adding, Deleting, and Updating
Records
• To add records to a table, use the INSERT and
VALUES keywords with the mysql_query()
function
• To add multiple records to a database, use the
LOAD DATA statement with the name of the
local text file containing the records you want to
add
• To update records in a table, use the UPDATE
statement
25PHP Programming with MySQL, 2nd Edition
Adding, Deleting, and Updating
Records (continued)
• The UPDATE keyword specifies the name of the
table to update
• The SET keyword specifies the value to assign
to the fields in the records that match the
condition in the WHERE clause
• To delete records in a table, use the DELETE
statement with the mysql_query() function
• Omit the WHERE clause to delete all records in a
table
26PHP Programming with MySQL, 2nd Edition
27PHP Programming with MySQL, 2nd Edition
Retrieving Records into an
Indexed Array
• The mysql_fetch_row() function returns the
fields in the current row of a resultset into an
indexed array and moves the result pointer to
the next row
echo "<table width='100%‘ border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Quantity</th></tr>";
$Row = mysql_fetch_row($QueryResult);
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = mysql_fetch_row($QueryResult);
} while ($Row);
28PHP Programming with MySQL, 2nd Edition
Using the mysql_affected_rows()
Function
• With queries that return results (SELECT
queries), use the mysql_num_rows() function
to find the number of records returned from the
query
• With queries that modify tables but do not return
results (INSERT, UPDATE, and DELETE queries),
use the mysql_affected_rows() function to
determine the number of affected rows
29PHP Programming with MySQL, 2nd Edition
Using the mysql_affected_rows()
Function (continued)
$SQLstring = "UPDATE company_cars SET mileage=50112.3
WHERE license='AK-1234'";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully updated "
. mysql_affected_rows($DBConnect) . "
record(s).</p>";
30PHP Programming with MySQL, 2nd Edition
Using the mysql_affected_rows()
Function (continued)
Figure 8-5 Output of mysql_affected_rows() function
for an UPDATE query
31PHP Programming with MySQL, 2nd Edition
Using the mysql_info() Function
• For queries that add or update records, or alter
a table’s structure, use the mysql_info()
function to return information about the query
• The mysql_info() function returns the
number of operations for various types of
actions, depending on the type of query
• The mysql_info() function returns information
about the last query that was executed on the
database connection
32PHP Programming with MySQL, 2nd Edition
Using the mysql_info() Function
(continued)
• The mysql_info() function returns information
about queries that match one of the following
formats:
– INSERT INTO...SELECT...
– INSERT INTO...VALUES (...),(...),(...)
– LOAD DATA INFILE ...
– ALTER TABLE ...
– UPDATE
• For any queries that do not match one of these
formats, the mysql_info() function returns an
empty string
33PHP Programming with MySQL, 2nd Edition
Using the mysql_info() Function
(continued)
$SQLstring = "INSERT INTO company_cars " .
" (license, model_year, make, model, mileage) " .
" VALUES " .
" ('CPQ-894', 2011, 'Honda', 'Insight', 49.2), " .
" ('CPQ-895', 2011, 'Honda', 'Insight', 17.9), " .
" ('CPQ-896', 2011, 'Honda', 'Insight', 22.6)";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
34PHP Programming with MySQL, 2nd Edition
Using the mysql_info() Function
(continued)
Figure 8-6 Output of mysql_info() function for an
INSERT query that adds multiple records
35PHP Programming with MySQL, 2nd Edition
Using the mysql_info() Function
(continued)
• The mysql_info() function also returns
information for LOAD DATA queries
$SQLstring = "LOAD DATA INFILE 'company_cars.txt'
INTO TABLE company_cars;";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else {
echo "<p>Successfully added the record.</p>";
echo "<p>" . mysql_info($DBConnect) . "</p>";
}
36PHP Programming with MySQL, 2nd Edition
Using the mysql_info() Function
(continued)
Figure 8-7 Output of mysql_info() function for a
LOAD DATA query
Working with Query Results
37PHP Programming with MySQL, 2nd Edition
Retrieving Records into an Indexed
Array
• The mysql_fetch_row() function returns the
fields in the current row of a result set into an
indexed array and moves the result pointer to
the next row
38PHP Programming with MySQL, 2nd Edition
Retrieving Records into an Indexed
Array
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
echo "<table width='100%' border='1'>n";
echo "<tr><th>License</th><th>Make</th><th>Model</th>
<th>Mileage</th><th>Year</th></tr>n";
while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>n";
}
echo "</table>n";
39PHP Programming with MySQL, 2nd Edition
Retrieving Records into an Indexed
Array
40PHP Programming with MySQL, 2nd Edition
Figure 8-8 Output of the company_cars table in a Web Browser
41PHP Programming with MySQL, 2nd Edition
Retrieving Records into an
Associative Array
• The mysql_fetch_assoc() function returns
the fields in the current row of a resultset into an
associative array and moves the result pointer to
the next row
• The difference between
mysql_fetch_assoc() and
mysql_fetch_row() is that instead of
returning the fields into an indexed array, the
mysql_fetch_assoc() function returns the
fields into an associate array and uses each field
name as the array key
42PHP Programming with MySQL, 2nd Edition
Closing Query Results
• When you are finished working with query
results retrieved with the mysql_query()
function, use the mysql_free_result()
function to close the resultset
• To close the resultset, pass to the
mysql_free_result() function the
variable containing the result pointer from the
mysql_query() function
43PHP Programming with MySQL, 2nd Edition
Accessing Query Result
Information
• The mysql_num_rows() function returns the
number of rows in a query result
• The mysql_num_fields() function returns the
number of fields in a query result
• Both functions accept a database connection
variable as an argument
44PHP Programming with MySQL, 2nd Edition
Accessing Query Result
Information (continued)
$SQLstring = "SELECT * FROM company_cars";
$QueryResult = @mysql_query($SQLstring, $DBConnect);
if ($QueryResult === FALSE)
echo "<p>Unable to execute the query.</p>"
. "<p>Error code " . mysql_errno($DBConnect)
. ": " . mysql_error($DBConnect) . "</p>";
else
echo "<p>Successfully executed the query.</p>";
$NumRows = mysql_num_rows($QueryResult);
$NumFields = mysql_num_fields($QueryResult);
if ($NumRows != 0 && $NumFields != 0)
echo "<p>Your query returned " .
mysql_num_rows($QueryResult) . " rows and "
. mysql_num_fields($QueryResult) . " fields.</p>";
else
echo "<p>Your query returned no results.</p>";
mysql_close($DBConnect);
45PHP Programming with MySQL, 2nd Edition
Accessing Query Result
Information (continued)
Figure 8-10 Output of the number of rows and fields
returned from a query
46PHP Programming with MySQL, 2nd Edition
Summary
• The mysql_connect() function opens a
connection to a MySQL database server
• The mysql_close() function closes a
database connection
• The mysql_errno() function returns the error
code from the last attempted MySQL function
call or zero if no error occurred
47PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The mysql_error() function returns the error
message from the last attempted MySQL
function call or an empty string if no error
occurred
• The error control operator (@) suppresses
error messages
• You use the mysql_create_db() function to
create a new database
• The mysql_select_db() function selects a
database
48PHP Programming with MySQL, 2nd Edition
Summary (continued)
• You use the mysql_drop_db() function to
delete a database
• The mysql_query() function sends SQL
statements to MySQL
• A result pointer is a special type of variable that
refers to the currently selected row in a resultset
• You use the CREATE TABLE statement with the
mysql_query() function to create a table
49PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The PRIMARY KEY clause indicates a field or
fields that will be used as a referential index for
the table
• The AUTO_INCREMENT clause creates a field
that is automatically updated with the next
sequential value for that column
• The NOT NULL clause creates a field that must
contain data
• You use the DROP TABLE statement with the
mysql_query() function to delete a table
50PHP Programming with MySQL, 2nd Edition
Summary (continued)
• You use the LOAD DATA statement and the
mysql_query() function with a local text file
to add multiple records to a database
• You use the UPDATE statement with the
mysql_query() function to update records in
a table
• You use the DELETE statement with the
mysql_query() function to delete records from
a table
51PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The mysql_info() function returns the
number of operations for various types of
actions, depending on the type of query.
• The mysql_fetch_row() function returns the
fields in the current row of a resultset into an
indexed array and moves the result pointer to
the next row.
52PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The mysql_fetch_assoc() function returns
the fields in the current row of a resultset into an
associative array and moves the result pointer to
the next row
• The mysql_free_result() function closes a
resultset
53PHP Programming with MySQL, 2nd Edition
Summary (continued)
• The mysql_num_rows() function returns the
number of rows in a query result, and the
mysql_num_fields() function returns the
number of fields in a query result
• With queries that return results, such as SELECT
queries, you can use the mysql_num_rows()
function to find the number of records returned
from the query

Weitere ähnliche Inhalte

Was ist angesagt?

Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsDave Stokes
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017Dave Stokes
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With MysqlHarit Kothari
 
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 sqlsaritasingh19866
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)Dave Stokes
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part IIFirdaus Adib
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...Dave Stokes
 

Was ist angesagt? (20)

Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017MySQL Replication Evolution -- Confoo Montreal 2017
MySQL Replication Evolution -- Confoo Montreal 2017
 
Postgresql
PostgresqlPostgresql
Postgresql
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
lab56_db
lab56_dblab56_db
lab56_db
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With 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
 
DataBase Management System Lab File
DataBase Management System Lab FileDataBase Management System Lab File
DataBase Management System Lab File
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
MySQL 8 -- A new beginning : Sunshine PHP/PHP UK (updated)
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
 

Ähnlich wie 9780538745840 ppt ch08 (20)

Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
Chapter 7 working with databases and my sql
Chapter 7 working with databases and my sqlChapter 7 working with databases and my sql
Chapter 7 working with databases and my sql
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
lab56_db
lab56_dblab56_db
lab56_db
 
Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
 
Python database access
Python database accessPython database access
Python database access
 
PHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHPPHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHP
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
 
Php summary
Php summaryPhp summary
Php summary
 
Using Mysql.pptx
Using Mysql.pptxUsing Mysql.pptx
Using Mysql.pptx
 
My sql with querys
My sql with querysMy sql with querys
My sql with querys
 
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 For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
My sql.ppt
My sql.pptMy sql.ppt
My sql.ppt
 

Mehr von Terry Yoast

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12Terry Yoast
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11Terry Yoast
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08Terry Yoast
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06Terry Yoast
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05Terry Yoast
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04Terry Yoast
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 

Mehr von Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Kürzlich hochgeladen

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Kürzlich hochgeladen (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

9780538745840 ppt ch08

  • 1. Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2nd Edition
  • 2. 2PHP Programming with MySQL, 2nd Edition Objectives In this chapter, you will: • Connect to MySQL from PHP • Work with MySQL databases using PHP • Create, modify, and delete MySQL tables with PHP • Use PHP to manipulate MySQL records • Use PHP to retrieve database records
  • 3. 3PHP Programming with MySQL, 2nd Edition Connecting to MySQL with PHP • PHP has the ability to access and manipulate any database that is ODBC compliant • PHP includes functionality that allows you to work directly with different types of databases, without going through ODBC • PHP supports SQLite, database abstraction layer functions, and PEAR DB
  • 4. 4PHP Programming with MySQL, 2nd Edition Determining which MySQL Package to Use • The mysqli (MySQL Improved) package became available with PHP 5 and is designed to work with MySQL version 4.1.3 and later • Earlier versions must use the mysql package • The mysqli package is the object-oriented equivalent of the mysql package
  • 5. 5PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection • Open a connection to a MySQL database server with the mysql_connect() function • The mysql_connect() function returns a positive integer if it connects to the database successfully or FALSE if it does not • Assign the return value from the mysql_connect() function to a variable that you can use to access the database in your script
  • 6. 6PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued) • The syntax for the mysql_connect() function is: $connection = mysql_connect("host" [, "user", "password"]); • The host argument specifies the host name where your MySQL database server is installed • The user and password arguments specify a MySQL account name and password
  • 7. 7PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued) • The database connection is assigned to the $DBConnect variable $DBConnect = mysql_connect("localhost", "dongosselin ", "rosebud"); • Close a database connection using the mysql_close() function mysql_close($DBConnect);
  • 8. 8PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued)
  • 9. 9PHP Programming with MySQL, 2nd Edition Opening and Closing a MySQL Connection (continued) Figure 8-1 MySQLInfo.php in a Web browser
  • 10. 10PHP Programming with MySQL, 2nd Edition Reporting MySQL Errors • Reasons for not connecting to a database server include: – The database server is not running – Insufficient privileges to access the data source – Invalid username and/or password
  • 11. Reporting MySQL Errors (continued) • The mysql_errno() function returns the error code from the last attempted MySQL function call or 0 if no error occurred • The mysql_errno() and mysql_error() functions return the results of the previous mysql*() function 11PHP Programming with MySQL, 2nd Edition
  • 12. 12PHP Programming with MySQL, 2nd Edition Suppressing Errors with the Error Control Operator • By default, functions in the mysql package display errors and warnings as they occur • Use the error control operator (@) to suppress error messages • The error control operator can be prepended to any expression although it is commonly used with expressions
  • 13. Creating a Database • Use the mysql_create_db() function to create a new database • The basic syntax for the mysql_create_db() is: $result = mysql_create_db( "dbname" [, connection]); • The mysql_create_db() returns a Boolean TRUE if successful or FALSE if there was an error 13PHP Programming with MySQL, 2nd Edition
  • 14. Creating a Database (continued) Figure 8-2 Error message when the mysql_create_db() function is unavailable because of insufficient privileges 14PHP Programming with MySQL, 2nd Edition
  • 15. 15PHP Programming with MySQL, 2nd Edition Selecting a Database • The syntax for the mysql_select_db() function is: mysql_select_db(database [, connection]); • The function returns a value of TRUE if it successfully selects a database or FALSE if it does not • For security purposes, you may choose to use an include file to connect to the MySQL server and select a database
  • 16. Deleting a Database • To delete a database, use the mysql_drop_db() function. • The format for the mysql_drop_db() function is: $Result = mysql_drop_db("dbname" [, connection]); • The function returns a value of TRUE if it successfully drops a database or FALSE if it does not 16PHP Programming with MySQL, 2nd Edition
  • 17. 17PHP Programming with MySQL, 2nd Edition Executing SQL Statements • Use the mysql_query() function to send SQL statements to MySQL • The syntax for the mysql_query() function is: mysql_query(query [, connection]); • The mysql_query() function returns one of three values: – For SQL statements that do not return results (CREATE DATABASE and CREATE TABLE statements) it returns a value of TRUE if the statement executes successfully
  • 18. 18PHP Programming with MySQL, 2nd Edition Executing SQL Statements (continued) – For SQL statements that return results (SELECT and SHOW statements) the mysql_query() function returns a result pointer that represents the query results • A result pointer is a special type of variable that refers to the currently selected row in a resultset – The mysql_query() function returns a value of FALSE for any SQL statements that fail, regardless of whether they return results
  • 19. Creating and Deleting Tables • Use the CREATE TABLE statement with the mysql_query() function to create a new table • Use the mysql_select_db() function before executing the CREATE TABLE statement to verify that you are in the right database 19PHP Programming with MySQL, 2nd Edition
  • 20. Creating and Deleting Tables (continued) $SQLstring = "CREATE TABLE drivers (name VARCHAR(100), " . "emp_no SMALLINT, hire_date DATE, " . "stop_date DATE)"; $QueryResult = @mysql_query($SQLstring, $DBConnect); if ($QueryResult===FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>"; else echo "<p>Successfully created the table.</p>"; 20PHP Programming with MySQL, 2nd Edition
  • 21. Creating and Deleting Tables (continued) Figure 8-3 Error code and message that displays when you attempt to create a table that already exists 21PHP Programming with MySQL, 2nd Edition
  • 22. 22PHP Programming with MySQL, 2nd Edition Creating and Deleting Tables (continued) • Use the SHOW TABLES LIKE command to prevent code from trying to create a table that already exists. • If the table does not exist, the mysql_num_rows()function will return a value of 0 rows $TableName = "subscribers"; $SQLstring = "SHOW TABLES LIKE '$TableName'"; $QueryResult = @mysql_query($SQLstring, $DBConnect);
  • 23. Creating and Deleting Tables (continued) • To identify a field as a primary key in MySQL, include the PRIMARY KEY keywords when you define a field with the CREATE TABLE statement • The AUTO_INCREMENT keyword is often used with a primary key to generate a unique ID for each new row in a table • The NOT NULL keywords are often used with primary keys to require that a field include a value 23PHP Programming with MySQL, 2nd Edition
  • 24. Creating and Deleting Tables (continued) • To delete a table, use the DROP TABLE statement with the mysql_query() function 24PHP Programming with MySQL, 2nd Edition
  • 25. Adding, Deleting, and Updating Records • To add records to a table, use the INSERT and VALUES keywords with the mysql_query() function • To add multiple records to a database, use the LOAD DATA statement with the name of the local text file containing the records you want to add • To update records in a table, use the UPDATE statement 25PHP Programming with MySQL, 2nd Edition
  • 26. Adding, Deleting, and Updating Records (continued) • The UPDATE keyword specifies the name of the table to update • The SET keyword specifies the value to assign to the fields in the records that match the condition in the WHERE clause • To delete records in a table, use the DELETE statement with the mysql_query() function • Omit the WHERE clause to delete all records in a table 26PHP Programming with MySQL, 2nd Edition
  • 27. 27PHP Programming with MySQL, 2nd Edition Retrieving Records into an Indexed Array • The mysql_fetch_row() function returns the fields in the current row of a resultset into an indexed array and moves the result pointer to the next row echo "<table width='100%‘ border='1'>"; echo "<tr><th>Make</th><th>Model</th> <th>Price</th><th>Quantity</th></tr>"; $Row = mysql_fetch_row($QueryResult); do { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td align='right'>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td></tr>"; $Row = mysql_fetch_row($QueryResult); } while ($Row);
  • 28. 28PHP Programming with MySQL, 2nd Edition Using the mysql_affected_rows() Function • With queries that return results (SELECT queries), use the mysql_num_rows() function to find the number of records returned from the query • With queries that modify tables but do not return results (INSERT, UPDATE, and DELETE queries), use the mysql_affected_rows() function to determine the number of affected rows
  • 29. 29PHP Programming with MySQL, 2nd Edition Using the mysql_affected_rows() Function (continued) $SQLstring = "UPDATE company_cars SET mileage=50112.3 WHERE license='AK-1234'"; $QueryResult = @mysql_query($SQLstring, $DBConnect); if ($QueryResult === FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>"; else echo "<p>Successfully updated " . mysql_affected_rows($DBConnect) . " record(s).</p>";
  • 30. 30PHP Programming with MySQL, 2nd Edition Using the mysql_affected_rows() Function (continued) Figure 8-5 Output of mysql_affected_rows() function for an UPDATE query
  • 31. 31PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function • For queries that add or update records, or alter a table’s structure, use the mysql_info() function to return information about the query • The mysql_info() function returns the number of operations for various types of actions, depending on the type of query • The mysql_info() function returns information about the last query that was executed on the database connection
  • 32. 32PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) • The mysql_info() function returns information about queries that match one of the following formats: – INSERT INTO...SELECT... – INSERT INTO...VALUES (...),(...),(...) – LOAD DATA INFILE ... – ALTER TABLE ... – UPDATE • For any queries that do not match one of these formats, the mysql_info() function returns an empty string
  • 33. 33PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) $SQLstring = "INSERT INTO company_cars " . " (license, model_year, make, model, mileage) " . " VALUES " . " ('CPQ-894', 2011, 'Honda', 'Insight', 49.2), " . " ('CPQ-895', 2011, 'Honda', 'Insight', 17.9), " . " ('CPQ-896', 2011, 'Honda', 'Insight', 22.6)"; $QueryResult = @mysql_query($SQLstring, $DBConnect); if ($QueryResult === FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>"; else { echo "<p>Successfully added the record.</p>"; echo "<p>" . mysql_info($DBConnect) . "</p>"; }
  • 34. 34PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) Figure 8-6 Output of mysql_info() function for an INSERT query that adds multiple records
  • 35. 35PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) • The mysql_info() function also returns information for LOAD DATA queries $SQLstring = "LOAD DATA INFILE 'company_cars.txt' INTO TABLE company_cars;"; $QueryResult = @mysql_query($SQLstring, $DBConnect); if ($QueryResult === FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>"; else { echo "<p>Successfully added the record.</p>"; echo "<p>" . mysql_info($DBConnect) . "</p>"; }
  • 36. 36PHP Programming with MySQL, 2nd Edition Using the mysql_info() Function (continued) Figure 8-7 Output of mysql_info() function for a LOAD DATA query
  • 37. Working with Query Results 37PHP Programming with MySQL, 2nd Edition
  • 38. Retrieving Records into an Indexed Array • The mysql_fetch_row() function returns the fields in the current row of a result set into an indexed array and moves the result pointer to the next row 38PHP Programming with MySQL, 2nd Edition
  • 39. Retrieving Records into an Indexed Array $SQLstring = "SELECT * FROM company_cars"; $QueryResult = @mysql_query($SQLstring, $DBConnect); echo "<table width='100%' border='1'>n"; echo "<tr><th>License</th><th>Make</th><th>Model</th> <th>Mileage</th><th>Year</th></tr>n"; while (($Row = mysql_fetch_row($QueryResult)) !== FALSE) { echo "<tr><td>{$Row[0]}</td>"; echo "<td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; echo "<td align='right'>{$Row[3]}</td>"; echo "<td>{$Row[4]}</td></tr>n"; } echo "</table>n"; 39PHP Programming with MySQL, 2nd Edition
  • 40. Retrieving Records into an Indexed Array 40PHP Programming with MySQL, 2nd Edition Figure 8-8 Output of the company_cars table in a Web Browser
  • 41. 41PHP Programming with MySQL, 2nd Edition Retrieving Records into an Associative Array • The mysql_fetch_assoc() function returns the fields in the current row of a resultset into an associative array and moves the result pointer to the next row • The difference between mysql_fetch_assoc() and mysql_fetch_row() is that instead of returning the fields into an indexed array, the mysql_fetch_assoc() function returns the fields into an associate array and uses each field name as the array key
  • 42. 42PHP Programming with MySQL, 2nd Edition Closing Query Results • When you are finished working with query results retrieved with the mysql_query() function, use the mysql_free_result() function to close the resultset • To close the resultset, pass to the mysql_free_result() function the variable containing the result pointer from the mysql_query() function
  • 43. 43PHP Programming with MySQL, 2nd Edition Accessing Query Result Information • The mysql_num_rows() function returns the number of rows in a query result • The mysql_num_fields() function returns the number of fields in a query result • Both functions accept a database connection variable as an argument
  • 44. 44PHP Programming with MySQL, 2nd Edition Accessing Query Result Information (continued) $SQLstring = "SELECT * FROM company_cars"; $QueryResult = @mysql_query($SQLstring, $DBConnect); if ($QueryResult === FALSE) echo "<p>Unable to execute the query.</p>" . "<p>Error code " . mysql_errno($DBConnect) . ": " . mysql_error($DBConnect) . "</p>"; else echo "<p>Successfully executed the query.</p>"; $NumRows = mysql_num_rows($QueryResult); $NumFields = mysql_num_fields($QueryResult); if ($NumRows != 0 && $NumFields != 0) echo "<p>Your query returned " . mysql_num_rows($QueryResult) . " rows and " . mysql_num_fields($QueryResult) . " fields.</p>"; else echo "<p>Your query returned no results.</p>"; mysql_close($DBConnect);
  • 45. 45PHP Programming with MySQL, 2nd Edition Accessing Query Result Information (continued) Figure 8-10 Output of the number of rows and fields returned from a query
  • 46. 46PHP Programming with MySQL, 2nd Edition Summary • The mysql_connect() function opens a connection to a MySQL database server • The mysql_close() function closes a database connection • The mysql_errno() function returns the error code from the last attempted MySQL function call or zero if no error occurred
  • 47. 47PHP Programming with MySQL, 2nd Edition Summary (continued) • The mysql_error() function returns the error message from the last attempted MySQL function call or an empty string if no error occurred • The error control operator (@) suppresses error messages • You use the mysql_create_db() function to create a new database • The mysql_select_db() function selects a database
  • 48. 48PHP Programming with MySQL, 2nd Edition Summary (continued) • You use the mysql_drop_db() function to delete a database • The mysql_query() function sends SQL statements to MySQL • A result pointer is a special type of variable that refers to the currently selected row in a resultset • You use the CREATE TABLE statement with the mysql_query() function to create a table
  • 49. 49PHP Programming with MySQL, 2nd Edition Summary (continued) • The PRIMARY KEY clause indicates a field or fields that will be used as a referential index for the table • The AUTO_INCREMENT clause creates a field that is automatically updated with the next sequential value for that column • The NOT NULL clause creates a field that must contain data • You use the DROP TABLE statement with the mysql_query() function to delete a table
  • 50. 50PHP Programming with MySQL, 2nd Edition Summary (continued) • You use the LOAD DATA statement and the mysql_query() function with a local text file to add multiple records to a database • You use the UPDATE statement with the mysql_query() function to update records in a table • You use the DELETE statement with the mysql_query() function to delete records from a table
  • 51. 51PHP Programming with MySQL, 2nd Edition Summary (continued) • The mysql_info() function returns the number of operations for various types of actions, depending on the type of query. • The mysql_fetch_row() function returns the fields in the current row of a resultset into an indexed array and moves the result pointer to the next row.
  • 52. 52PHP Programming with MySQL, 2nd Edition Summary (continued) • The mysql_fetch_assoc() function returns the fields in the current row of a resultset into an associative array and moves the result pointer to the next row • The mysql_free_result() function closes a resultset
  • 53. 53PHP Programming with MySQL, 2nd Edition Summary (continued) • The mysql_num_rows() function returns the number of rows in a query result, and the mysql_num_fields() function returns the number of fields in a query result • With queries that return results, such as SELECT queries, you can use the mysql_num_rows() function to find the number of records returned from the query