You are on page 1of 21

Chapter 4 PHP with MySQL Slide 1

CHAPTER 4:
PHP with MySQL
Topics covered:-
Connecting to MySQL
SQL Insert, Update, Delete, Select
Secure SQL

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 2

Learning Outcomes
At the end of this chapter, you should be able to :

Connect to MySQL from PHP


Create, modify, and delete MySQL tables with PHP
Use PHP to manipulate MySQL records
Use PHP to retrieve database records

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 3

Introduction (1)
• 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
• For information of data types supported in MySQL, refer to the
document “List of MySQL Data Types.doc”
• For details of functions and commands available in MySQL,
refer to MySQL reference manual at
http://dev.mysql.com/doc/

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 4

Introduction (2)
• Basic steps in querying database from the web
1. Validate data submitted by the user
2. Set up the connection to the database
3. Query the database
4. For a SELECT query, 2 further steps involved
4.1 Retrieve results
4.2 Present results back to the user
5. Disconnect from the database

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 5

Connecting to MySQL (1)


• Open a connection to a MySQL database server with the
mysqli_connect() function
• Syntax:
$dbc = mysqli_connect (host,
username, password, db_name);
 host specifies the host name where the MySQL database server is
installed
 username and password arguments specify a MySQL account name and
password
• The mysqli_connect() function returns a positive integer if it
connects to the database successfully or FALSE if it does not
• To check connection error, use
mysqli_connect_error()
which returns the connection error message.

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 6

Connecting to MySQL (2)


<? php //mysqli_connect.php
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'sitename');
// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER,
DB_PASSWORD, DB_NAME) OR
die ('Could not connect to MySQL:
'.mysqli_connect_error() ); ?>
die (..) will execute if mysqli_connect fails to return a valid resource link. The die()
function terminates the execution of the script
By default, functions in the mysqli package display errors and warnings as they
occur
Use the error control operator (@) to suppress error messages
AMIT 2043 Web Systems and Technologies
Chapter 4 PHP with MySQL Slide 7

Connecting to MySQL (3)


• 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

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 8

Connecting to MySQL (4)


• If a database has not been selected when establishing a
connection to MySQL, omit that argument from the
mysqli_connect() function:

$dbc = mysqli_connect (host, username,


password);

• Then, when appropriate, one can select the database using


mysqli_select_db($dbc, db_name);

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 9

Query the Database (1)


• Use the mysqli_query() function to send SQL statements to MySQL
• Syntax:
$result = mysqli_query($dbc, $q);
$q can be either SELECT, INSERT, UPDATE,
or DELETE statements
• The mysqli_query() function returns one of 3 values:
• For SQL statements that do not return records (INSERT, UPDATE,
DELETE statements) it returns a value of TRUE if the statement
executes successfully
• For queries that return records (eg SELECT), $result will be a resource
link to the results of the query
• A value of FALSE will be returned for any SQL statements that fail,
regardless of whether they return results. mysqli_error() function
can be used to display the error.

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 10
// register.php
require_once ('mysqli_connect.php'); // Connect to the db.
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ('$fn',
'$ln', '$e', SHA1('$p'), NOW() )";
$result = @mysqli_query ($dbc, $q);
if ($result) { // successful
echo '<h1>Thank you!</h1><p>You are now registered.</p><p><br /></p>';
} else { // If it failed
echo '<h1>System Error</h1>
<p>You could not be registered due to a system error. We apologize for any
inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>' }

Note : SHA1() function is used for encrypting data and NOW() function returns
current date and time
AMIT 2043 Web Systems and Technologies
Chapter 4 PHP with MySQL Slide 11

Query the Database (2)


• With queries that return results (SELECT queries), use the
mysql_num_rows() function to find the number of records
returned from the query.
Usage of mysql_num_rows()
• Paginate the query results
• Validation
Check if a query returns any result
Check whether a user-supplied data is unique

• 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

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 12
// retrieve_forums.php
require_once ('mysqli_connect.php');
$q = "SELECT * FROM messages, forums WHERE forums.forum_id =
messages.forum_id and forums.forum_id=1";

$r = @mysqli_query ($dbc, $q); // Run the query.

// Count the number of returned rows:


$num = mysqli_num_rows($r);
if ($num > 0) { // If it ran OK, display result.
echo "<p>There are currently $num messages for forum 1.</p>\n";
mysqli_free_result ($r); // Free up the resources.
} else { // If no records were returned.
echo '<p>There are currently no messages.</p>';
}
AMIT 2043 Web Systems and Technologies
Chapter 4 PHP with MySQL Slide 13
// housekeeping.php
require_once ('mysqli_connect.php');
$q = "SELECT * FROM messages WHERE YEAR(date_entered) < 2007";
$r = @mysqli_query ($dbc, $q); // Run the query.
// Count the number of returned rows:
$num = mysqli_num_rows($r);
if ($num > 0) { // If it ran OK, display result.
echo "<p>There are currently $num messages before 2007</p>\n";
mysqli_free_result ($r); // Free up the resources.
$q = "DELETE FROM messages WHERE YEAR(date_entered) < 2007";
$r = @mysqli_query ($dbc, $q); // Run the query.
echo "mysqli_affected_rows($dbc) have been deleted from the database.";
} else { // If no records were returned.
echo '<p>There are currently no message before 2007.</p>';
}

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 14

Retrieving Query Results (1)


• To handle SELECT query results, use
mysqli_fetch_array(), which returns one row of data
at a time in an array format.

• To read each record from a query,


mysqli_fetch_array() should be used within a loop

while ($row = mysqli_fetch_array($r)) {


// Do something with $row.
}

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 15
//view_users.php
$q = "SELECT CONCAT(last_name, ', ', first_name) AS name,
DATE_FORMAT(registration_date, '%M %d, %Y') AS dr FROM users ORDER BY
registration_date ASC";
$r = @mysqli_query ($dbc, $q); // Run the query.
if ($r) { // If it ran OK, display the records.
// Table header.
echo '<table > <tr><td align="left"><b>Name</b></td>
<td align="left"><b>Date Registered</b></td></tr>';
// Fetch and print all the records:
while ($row = mysqli_fetch_array($r)) {
echo '<tr><td align="left">' . $row['name'] . '</td><td align="left">' .
$row['dr'] . '</td></tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($r); // Free up the resources. }
else { // If it did not run OK. ……
}

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 16

Retrieving Query Results (2)


• The mysqli_fetch_array() function takes an optional second
parameter specifying what type of array is returned:
associative, indexed, or both (default). Each parameter is
defined by a constant
MYSQLI_ASSOC $row['column']

MYSQLI_NUM $row[0]

MYSQLI_BOTH $row[0] or $row['column']

mysqli_free_result () function is used to free the


resources taken by the query result. It’s an optional step,
since PHP will automatically free up the resources

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 17
// Check that they've entered the right email address/password combination:
$q = "SELECT user_id FROM users WHERE (email='$e' AND pass=SHA1('$p') )";
$r = @mysqli_query($dbc, $q);
$num = @mysqli_num_rows($r);
if ($num == 1) { // Match was made.
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Make the UPDATE query:
$q = "UPDATE users SET pass=SHA1('$np') WHERE user_id=$row[0]";
$r = @mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
echo '<h1>Thank you!</h1><p>Your password has been updated. </p><p><br /></p>';
} else { // If it did not run OK.
echo '<h1>System Error</h1>
<p class="error">Your password could not be changed due to a system error.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
} else { // Invalid email address/password combination.
echo '<h1>Error!</h1><p class="error">The email address and password do not match
those on file.</p>';
}
AMIT 2043 Web Systems and Technologies
Chapter 4 PHP with MySQL Slide 18

Closing a MySQL Connection


• Close a database connection using the mysqli_close()
function
Eg:
mysqli_close($dbc);
• This function is optional, because PHP will automatically
close the connection at the end of a script
• A good programming practice to explicit close the
connection

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 19

Ensuring Secure SQL (1)


• Three broad issues concerning database security with respect to PHP
Issue Solution
Protecting the Store the MySQL connection script outside of the
MySQL access Web directory so that it is not viewable through a
information Web browser.
Not revealing too Error messages on SQL queries should not be
much about the displayed to the user.
database
Being cautious when 1. Validate form data to ensure that some value has
running queries, been submitted and it is of the correct type and
particularly those format.
involving user- 2. Use mysqli_real_escape_string() function to clean
supplied data data by escaping what could be problematic
characters.

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 20

Ensuring Secure SQL (2)


• Example using mysqli_real_escape_string:
if (empty($_POST['first_name'])) {
$errors[] = 'You forgot to enter your
first name.';
} else {
$fn = mysqli_real_escape_string($dbc,
trim($_POST['first_name']));
}

PhpProject6\register_v2.php

AMIT 2043 Web Systems and Technologies


Chapter 4 PHP with MySQL Slide 21

References
• PHP 6 and MySQL 5 by Ullman, L. Peachpit Press

• PHP Programming with MySQL Second Edition


by Gosselin, D., Kokoska, D. & Easterbrooks, R.
Course Technology

AMIT 2043 Web Systems and Technologies

You might also like