Chapter 01 Part2 1.2.2
Chapter 01 Part2 1.2.2
C1, Slide 2
1.2.2. How to use PHP with a Mysql database
Objectives
Applied
1. Given the specifications for a database application that requires
only the skills that are presented in this chapter, develop the
application. That includes:
Connecting to a MySQL database
Handling PDO exceptions
Using prepared statements to execute SQL statements
Getting the data from the result sets that are returned by SQL
statements
C4, Slide 3
1.2.2. How to use PHP with a Mysql database
Objectives (continued)
Knowledge
1. Describe the PHP code for creating a PDO object that connects to a
MySQL database.
2. Describe the PHP code for handling the PDO exceptions that may
occur when you try to create a PDO object.
3. List two reasons you should use prepared statements for production
applications.
4. Describe how to use a prepared statement to execute a SELECT,
INSERT, UPDATE, or DELETE statement.
5. Describe a PHP array and the way that numeric and string indexes
are used to access the data in a PHP array.
6. Distinguish between the fetch() and fetchAll() methods of the
PDOStatement class.
7. Describe how to use a foreach statement to get data from all rows
of a result set.
C4, Slide 4
The syntax for creating an object from any
class
new ClassName(arguments);
C4, Slide 5
How to connect to a MySQL database
$dsn = 'mysql:host=localhost;dbname=my_guitar_shop1';
$username = 'mgs_user';
$password = 'pa55word';
C4, Slide 6
Key terms
class
object
new keyword
argument
PDO object
DSN (Data Source Name)
PDO (PHP Data objects) extension
C4, Slide 7
The syntax for a try/catch statement
try {
// statements that might throw an exception
} catch (ExceptionClass $exception_name) {
// statements that handle the exception
}
C4, Slide 8
How to handle a PDO exception
try {
$db = new PDO($dsn, $username, $password);
echo '<p>You are connected to the database!</p>';
} catch (PDOException $e) {
$error_message = $e->getMessage();
echo "<p>An error occurred while connecting to
the database: $error_message </p>";
}
C4, Slide 9
Key terms
exception
exception handling
throw an exception
try/catch statement
try block
catch block
method
Exception class
PDOException class
C4, Slide 10
A method of the PDO class
for preparing a SQL statement
prepare($select_statement)
C4, Slide 11
How to execute a SQL statement
that doesn’t have parameters
$query = 'SELECT * FROM products';
$statement = $db->prepare($query);
$statement->execute();
C4, Slide 12
Two more methods of the PDOStatement class
fetch()
closeCursor()
C4, Slide 13
Code that uses a string index
to access each column
$product_code = $product['productCode'];
$product_name = $product['productName'];
$product_list_price = $product['listPrice'];
C4, Slide 14
Key terms
array
elements
index
C4, Slide 15
Another method of the PDOStatement class
fetchAll()
C4, Slide 16
How to use a foreach statement
to display the result set in an HTML table
<?php foreach ($products as $product) { ?>
<tr>
<td><?php echo $product['productCode']; ?></td>
<td><?php echo $product['productName']; ?></td>
<td><?php echo $product['listPrice']; ?></td>
</tr>
<?php } ?>
C4, Slide 17
Key terms
foreach statement
foreach loop
C4, Slide 18
How to execute an INSERT statement
$category_id = 1;
$code = 'strat';
$name = 'Fender Stratocaster';
$price = 699.99;
$statement = $db->prepare($query);
$statement->bindValue(':category_id', $category_id);
$statement->bindValue(':code', $code);
$statement->bindValue(':name', $name);
$statement->bindValue(':price', $price);
$statement->execute();
$statement->closeCursor();
C4, Slide 19
How to execute an UPDATE statement
$product_id = 4;
$price = 599.99;
$statement = $db->prepare($query);
$statement->bindValue(':price', $price);
$statement->bindValue(':product_id', $product_id);
$statement->execute();
$statement->closeCursor();
C4, Slide 20
How to execute a DELETE statement
$product_id = 4;
$statement = $db->prepare($query);
$statement->bindValue(':product_id', $product_id);
$statement->execute();
$statement->closeCursor();
C4, Slide 21
The user interface
C4, Slide 22
The user interface after the user
selects a new category
C4, Slide 23
The database.php file
<?php
$dsn = 'mysql:host=localhost;dbname=my_guitar_shop1';
$username = 'mgs_user';
$password = 'pa55word';
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
C4, Slide 24
The database_error.php file
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
C4, Slide 25
The index.php file
<?php
require('database.php');
// Get category ID
$category_id = filter_input(INPUT_GET, 'category_id',
FILTER_VALIDATE_INT);
if ($category_id == NULL || $category_id == FALSE) {
$category_id = 1;
}
C4, Slide 26
The index.php file (continued)
// Get all categories
$queryAllCategories = 'SELECT * FROM categories
ORDER BY categoryID';
$statement2 = $db->prepare($queryAllCategories);
$statement2->execute();
$categories = $statement2->fetchAll();
$statement2->closeCursor();
C4, Slide 27
The index.php file (continued)
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<!-- the body section -->
<body>
<main>
<h1>Product List</h1>
<aside>
<!-- display a list of categories -->
<h2>Categories</h2>
<nav>
<ul>
<?php foreach ($categories as $category) : ?>
<li>
<a href="?category_id=<?php echo
$category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</a>
</li>
C4, Slide 28
The index.php file (continued)
<?php endforeach; ?>
</ul>
</nav>
</aside>
<section>
<!-- display a table of products -->
<h2><?php echo $category_name; ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th class="right">Price</th>
</tr>
C4, Slide 29
The index.php file (continued)
<?php foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productCode']; ?></td>
<td><?php echo $product['productName']; ?></td>
<td class="right"><?php echo
$product['listPrice']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</section>
</main>
<footer></footer>
</body>
</html>
C4, Slide 30
The Product List page
C4, Slide 31
The Add Product page
C4, Slide 32
The index.php file
<?php
require_once('database.php');
// Get category ID
if (!isset($category_id)) {
$category_id = filter_input(INPUT_GET, 'category_id',
FILTER_VALIDATE_INT);
if ($category_id == NULL || $category_id == FALSE) {
$category_id = 1;
}
}
C4, Slide 33
The index.php file (continued)
// Get all categories
$queryAllCategories = 'SELECT * FROM categories
ORDER BY categoryID';
$statement2 = $db->prepare($queryAllCategories);
$statement2->execute();
$categories = $statement2->fetchAll();
$statement2->closeCursor();
C4, Slide 34
The index.php file (continued)
<!DOCTYPE html>
<html>
C4, Slide 35
The index.php file (continued)
<aside>
<!-- display a list of categories -->
<h2>Categories</h2>
<nav>
<ul>
<?php foreach ($categories as $category) : ?>
<li><a href=".?category_id=<?php echo
$category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</aside>
C4, Slide 36
The index.php file (continued)
<section>
<!-- display a table of products -->
<h2><?php echo $category_name; ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th class="right">Price</th>
<th> </th>
</tr>
C4, Slide 37
The index.php file (continued)
<td><form action="delete_product.php" method="post">
<input type="hidden" name="product_id"
value="<?php echo $product['productID']; ?>">
<input type="hidden" name="category_id"
value="<?php echo $product['categoryID']; ?>">
<input type="submit" value="Delete">
</form></td>
</tr>
<?php endforeach; ?>
</table>
<p><a href="add_product_form.php">Add Product</a></p>
</section>
</main>
<footer>
<p>© <?php echo date("Y"); ?> My Guitar Shop, Inc.</p>
</footer>
</body>
</html>
C4, Slide 38
The delete_product.php file
<?php
require_once('database.php');
C4, Slide 39
The add_product_form.php file
<?php
require('database.php');
$query = 'SELECT *
FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$categories = $statement->fetchAll();
$statement->closeCursor();
?>
C4, Slide 40
The add_product_form.php file (continued)
<!DOCTYPE html>
<html>
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<header><h1>Product Manager</h1></header>
<main>
<h1>Add Product</h1>
<form action="add_product.php" method="post"
id="add_product_form">
<label>Category:</label>
<select name="category_id">
<?php foreach ($categories as $category) : ?>
<option value="<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</option>
<?php endforeach; ?>
</select><br>
C4, Slide 41
The add_product_form.php file (continued)
<label>Code:</label>
<input type="text" name="code"><br>
<label>Name:</label>
<input type="text" name="name"><br>
<label>List Price:</label>
<input type="text" name="price"><br>
<label> </label>
<input type="submit" value="Add Product"><br>
</form>
<p><a href="index.php">View Product List</a></p>
</main>
<footer>
<p>© <?php echo date("Y"); ?> My Guitar Shop, Inc.</p>
</footer>
</body>
</html>
C4, Slide 42
The add_product.php file
<?php
// Get the product data
$category_id = filter_input(INPUT_POST, 'category_id',
FILTER_VALIDATE_INT);
$code = filter_input(INPUT_POST, 'code');
$name = filter_input(INPUT_POST, 'name');
$price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
// Validate inputs
if ($category_id == null || $category_id == false || $code == null
|| $name == null || $price == null || $price == false ) {
$error = "Invalid product data. Check all fields and try
again.";
include('error.php');
} else {
require_once('database.php');
C4, Slide 43
The add_product.php file (continued)
// Add the product to the database
$query = 'INSERT INTO products
(categoryID, productCode, productName, listPrice)
VALUES
(:category_id, :code, :name, :price)';
$statement = $db->prepare($query);
$statement->bindValue(':category_id', $category_id);
$statement->bindValue(':code', $code);
$statement->bindValue(':name', $name);
$statement->bindValue(':price', $price);
$statement->execute();
$statement->closeCursor();
C4, Slide 44