SlideShare a Scribd company logo
1 of 60
Download to read offline
2
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
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
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 but can also be
used procedurally
• Mysqli package has improved speed, security and
compatibility with libraries.
5
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
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
Opening and Closing a MySQL
Connection (continued)
• The database connection is assigned to the
$DBConnect variable
$DBConnect = mysql_connect("localhost",
“root", “myPassword");
• Close a database connection using the
mysql_close() function
mysql_close($DBConnect);
8
Opening and Closing a MySQL
Connection (continued)
Opening and Closing a MySQL
Connection (continued)
9
10
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_error() — Returns the text of the
error message from previous MySQL operation
• The mysql_errno() and mysql_error()
functions return the results of the previous
mysql*() function
11
12
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
Sample Code
$link = mysql_connect(“localhost", “root", “passwd");
mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "n";
mysql_select_db(“myDatabase", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "n";
13
good
bad
good
bad
Sample Code
$host = 'localhost';
$userName = 'root';
$password = '*****';
$database = 'myDatabase';
$link = mysql_connect ($host, $userName, $password );
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
14
Sample Code
<?php
$link = mysql_connect('localhost', root', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db(my_database', $link);
if (!$db_selected) {
die ('Can't use foo : ' . mysql_error());
}
?>
15
16
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
17
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
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
Sample Code
<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
//never trust user data
$firstname= mysql_real_escape_string($firstname);
$lastname= mysql_real_escape_string($lastname);
// Formulate Query
// For more examples, see mysql_real_escape_string()
$query = "SELECT firstname, lastname, address, age FROM friends WHERE firstname=‘$firstname ‘ AND lastname= ‘$lastname’”;
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
19
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
20
Adding, Deleting, and Updating
Records
<?php
$con = mysql_connect("localhost",“root",“my_password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
21
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
22
Adding, Deleting, and Updating
Records
<?php
$con = mysql_connect("localhost",“root",“my_password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
mysql_close($con);
?>
23
24
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);
Sample Code
<?php
$conn = mysql_connect("localhost", "mysql_user",
"mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_err
or();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) fro
m DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiti
ng";
exit;
}
// While a row of data exists, put that row in $row a
s an associative array
// Note: If you're expecting just one row, no need to
use a loop
// Note: If you put extract($row); inside the following
loop, you'll
// then create $userid, $fullname, and $userstat
us
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
25
26
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
27
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>";
28
Using the mysql_affected_rows()
Function (continued)
29
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
30
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
31
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>";
}
32
Using the mysql_info() Function
(continued)
33
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>";
}
34
Using the mysql_info() Function
(continued)
Working with Query Results
35
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
36
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";
37
Retrieving Records into an Indexed
Array
38
39
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
40
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
41
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
42
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);
43
Accessing Query Result
Information (continued)
44
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
45
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
46
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
47
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
48
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 – MAY NOT
WORK ON PARADOX
• 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
49
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.
50
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
51
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
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
52
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>";
53
Creating and Deleting Tables
(continued)
54
55
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
56
Creating and Deleting Tables
(continued)
• To delete a table, use the DROP TABLE
statement with the mysql_query()
function
57
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
• In most cases we will use mysql monitor,
PhpMyAdmin or Workbench to create databases. 58
Creating a Database (continued)
59
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
60

More Related Content

What's hot

Database presentation
Database presentationDatabase presentation
Database presentationwebhostingguy
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
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
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08Terry Yoast
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With MysqlHarit Kothari
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Developmentw3ondemand
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sqlsalissal
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsDave Stokes
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptFramgia Vietnam
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboardsDenis Ristic
 
Php and database functionality
Php and database functionalityPhp and database functionality
Php and database functionalitySayed Ahmed
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09Terry Yoast
 

What's hot (19)

Database presentation
Database presentationDatabase presentation
Database presentation
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
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
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
 
Mysql
MysqlMysql
Mysql
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 
lab56_db
lab56_dblab56_db
lab56_db
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
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
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
MySQL
MySQLMySQL
MySQL
 
Advanced MySQL Query Optimizations
Advanced MySQL Query OptimizationsAdvanced MySQL Query Optimizations
Advanced MySQL Query Optimizations
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
 
15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards15 MySQL Basics #burningkeyboards
15 MySQL Basics #burningkeyboards
 
Php and database functionality
Php and database functionalityPhp and database functionality
Php and database functionality
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09
 

Similar to PHP with MySQL

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erickokelloerick
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For BeginnersPriti Solanki
 
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 CollegeDhivyaa C.R
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8Mohd Harris Ahmad Jaal
 
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.docxmoirarandell
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRsquared Academy
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13Hassen Poreya
 
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 NewbiesDave Stokes
 
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 7Mohd Harris Ahmad Jaal
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Databasedharawagh9999
 

Similar to PHP with MySQL (20)

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
Php summary
Php summaryPhp summary
Php summary
 
Php verses my sql
Php verses my sqlPhp verses my sql
Php verses my sql
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
Php verses MySQL
Php verses MySQLPhp verses MySQL
Php verses MySQL
 
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
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8
 
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
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
MySQL Record Operations
MySQL Record OperationsMySQL Record Operations
MySQL Record Operations
 
Python database access
Python database accessPython database access
Python database access
 
Web app development_crud_13
Web app development_crud_13Web app development_crud_13
Web app development_crud_13
 
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
 
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
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 

More from wahidullah mudaser

AJAX-Asynchronous JavaScript and XML
AJAX-Asynchronous JavaScript and XMLAJAX-Asynchronous JavaScript and XML
AJAX-Asynchronous JavaScript and XMLwahidullah mudaser
 
XML - Extensive Markup Language
XML - Extensive Markup LanguageXML - Extensive Markup Language
XML - Extensive Markup Languagewahidullah mudaser
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. wahidullah mudaser
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPwahidullah mudaser
 

More from wahidullah mudaser (6)

AJAX-Asynchronous JavaScript and XML
AJAX-Asynchronous JavaScript and XMLAJAX-Asynchronous JavaScript and XML
AJAX-Asynchronous JavaScript and XML
 
XML - Extensive Markup Language
XML - Extensive Markup LanguageXML - Extensive Markup Language
XML - Extensive Markup Language
 
PHP file handling
PHP file handling PHP file handling
PHP file handling
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array.
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 

Recently uploaded

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

PHP with MySQL

  • 1.
  • 2. 2 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. 3 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. 4 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 but can also be used procedurally • Mysqli package has improved speed, security and compatibility with libraries.
  • 5. 5 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. 6 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. 7 Opening and Closing a MySQL Connection (continued) • The database connection is assigned to the $DBConnect variable $DBConnect = mysql_connect("localhost", “root", “myPassword"); • Close a database connection using the mysql_close() function mysql_close($DBConnect);
  • 8. 8 Opening and Closing a MySQL Connection (continued)
  • 9. Opening and Closing a MySQL Connection (continued) 9
  • 10. 10 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_error() — Returns the text of the error message from previous MySQL operation • The mysql_errno() and mysql_error() functions return the results of the previous mysql*() function 11
  • 12. 12 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
  • 13. Sample Code $link = mysql_connect(“localhost", “root", “passwd"); mysql_select_db("nonexistentdb", $link); echo mysql_errno($link) . ": " . mysql_error($link). "n"; mysql_select_db(“myDatabase", $link); mysql_query("SELECT * FROM nonexistenttable", $link); echo mysql_errno($link) . ": " . mysql_error($link) . "n"; 13 good bad good bad
  • 14. Sample Code $host = 'localhost'; $userName = 'root'; $password = '*****'; $database = 'myDatabase'; $link = mysql_connect ($host, $userName, $password ); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); 14
  • 15. Sample Code <?php $link = mysql_connect('localhost', root', 'mysql_password'); if (!$link) { die('Not connected : ' . mysql_error()); } // make foo the current db $db_selected = mysql_select_db(my_database', $link); if (!$db_selected) { die ('Can't use foo : ' . mysql_error()); } ?> 15
  • 16. 16 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
  • 17. 17 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. 18 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. Sample Code <?php // This could be supplied by a user, for example $firstname = 'fred'; $lastname = 'fox'; //never trust user data $firstname= mysql_real_escape_string($firstname); $lastname= mysql_real_escape_string($lastname); // Formulate Query // For more examples, see mysql_real_escape_string() $query = "SELECT firstname, lastname, address, age FROM friends WHERE firstname=‘$firstname ‘ AND lastname= ‘$lastname’”; // Perform Query $result = mysql_query($query); // Check result // This shows the actual query sent to MySQL, and the error. Useful for debugging. if (!$result) { $message = 'Invalid query: ' . mysql_error() . "n"; $message .= 'Whole query: ' . $query; die($message); } // Use result // Attempting to print $result won't allow access to information in the resource // One of the mysql result functions must be used // See also mysql_fetch_array(), mysql_fetch_row(), etc. while ($row = mysql_fetch_assoc($result)) { echo $row['firstname']; echo $row['lastname']; echo $row['address']; echo $row['age']; } // Free the resources associated with the result set // This is done automatically at the end of the script mysql_free_result($result); ?> 19
  • 20. 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 20
  • 21. Adding, Deleting, and Updating Records <?php $con = mysql_connect("localhost",“root",“my_password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); mysql_close($con); ?> 21
  • 22. 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 22
  • 23. Adding, Deleting, and Updating Records <?php $con = mysql_connect("localhost",“root",“my_password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("UPDATE Persons SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); mysql_close($con); ?> 23
  • 24. 24 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);
  • 25. Sample Code <?php $conn = mysql_connect("localhost", "mysql_user", "mysql_password"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } if (!mysql_select_db("mydbname")) { echo "Unable to select mydbname: " . mysql_err or(); exit; } $sql = "SELECT id as userid, fullname, userstatus FROM sometable WHERE userstatus = 1"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) fro m DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiti ng"; exit; } // While a row of data exists, put that row in $row a s an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstat us while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } mysql_free_result($result); ?> 25
  • 26. 26 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
  • 27. 27 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>";
  • 29. 29 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
  • 30. 30 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
  • 31. 31 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>"; }
  • 32. 32 Using the mysql_info() Function (continued)
  • 33. 33 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>"; }
  • 34. 34 Using the mysql_info() Function (continued)
  • 35. Working with Query Results 35
  • 36. 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 36
  • 37. 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"; 37
  • 38. Retrieving Records into an Indexed Array 38
  • 39. 39 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
  • 40. 40 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
  • 41. 41 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
  • 42. 42 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);
  • 44. 44 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
  • 45. 45 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
  • 46. 46 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
  • 47. 47 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
  • 48. 48 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 – MAY NOT WORK ON PARADOX • 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
  • 49. 49 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.
  • 50. 50 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
  • 51. 51 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
  • 52. 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 52
  • 53. 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>"; 53
  • 54. Creating and Deleting Tables (continued) 54
  • 55. 55 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);
  • 56. 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 56
  • 57. Creating and Deleting Tables (continued) • To delete a table, use the DROP TABLE statement with the mysql_query() function 57
  • 58. 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 • In most cases we will use mysql monitor, PhpMyAdmin or Workbench to create databases. 58
  • 59. Creating a Database (continued) 59
  • 60. 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 60