Weitere ähnliche Inhalte Kürzlich hochgeladen (20) Part 21. Chapter 4
How to use PHP
with a MySQL database
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 1
2. Homework
• If you have not installed the Murach databases for
the guitar shop, DO IT ALREADY!
• If you are having trouble, please let us know
– See Jim, See me…
• P.122, Exercises 8, 9, 10, 11, 12, 13
– Any questions?
• Continue to explore the Guitar Shop
• If necessary, debug calculate_click()
– That function was fine, but there was a problem!
• Modify the future_value.js code to use an
is_input_valid function Murach &similar)
Murach's PHP and MySQL, C3 © 2010, Mike
(or Associates, Inc.
Slide 2
3. future_value.js
• Replace some of the repetitive logic with a
function
• Lots of ways to do this from the simple to the
complex
– I did the simple!
– Steve did a bit more complex
– Wallace added some shiny chrome!
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 3
5. Walk through an example – /book_apps/ch04_product_viewer
The user interface
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 5
6. The user interface after the user
selects a new category
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 6
7. The index.php file
<?php
require 'database.php';
// Get category ID
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch();
$category_name = $category['categoryName'];
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$categories = $db->query($query);
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 7
8. 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();
}
?>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 8
10. The syntax for creating an object from any class
new ClassName(arguments);
The syntax for creating a database object
from the PDO class
new PDO($dsn, $username, $password);
The syntax for a DSN (Data Source Name)
for a MySQL database
mysql:host=host_address;dbname=database_name
How to connect to a MySQL database
$dsn = 'mysql:host=localhost;dbname=my_guitar_shop1';
$username = 'mgs_user';
$password = 'pa55word';
// creates PDO object
$db = new PDO($dsn, $username, $password);
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 10
12. The syntax for a try/catch statement
try {
// statements that might throw an exception
} catch (ExceptionClass $exception_name) {
// statements that handle the exception
}
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>";
}
How to handle any type of exception
try {
// statements that might throw an exception
} catch (Exception $e) {
$error_message = $e->getMessage();
echo "<p>Error message: $error_message </p>";
}
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 12
13. The database.php file (continued)
<?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();
}
?>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 13
14. The database_error.php file
<!-- the head section -->
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css"
href="main.css" />
</head>
<!-- the body section -->
<body>
<div id="page">
<div id="main">
<h1>Database Error</h1>
<p>There was a database connection error.</p>
<p>The database must be installed.</p>
<p>MySQL must be running.</p>
<p>Error message:
<?php echo $error_message; ?></p>
</div>
</div><!-- end page -->
</body>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 14
15. The index.php file (REVISITED)
<?php
require 'database.php';
// Get category ID
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
} Since we are using the
PDO class, we use the
// Get name for current category PDO class methods:
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
query() and fetch().
$category = $db->query($query);
$category = $category->fetch(); Query() returns a PDO
$category_name = $category['categoryName']; result object which, in
// Get all categories essence, is a table –
$query = 'SELECT * FROM categories an array of arrays!
ORDER BY categoryID';
$categories = $db->query($query); Fetch() pulls the next
row from returned
table.
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 15
16. The index.php file (continued)
// Get products for selected category
$query = "SELECT * FROM products
WHERE categoryID = $category_id
ORDER BY productID";
$products = $db->query($query);
?>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 16
17. A method of the PDO class
for executing a SELECT statement
query($select_statement)
The syntax for executing a method of any object
$objectName->methodName(argumentList)
The syntax for executing the query method
of the database object
$PDO_object->query($select_statement)
A query method with the SELECT statement
in a variable
$query = 'SELECT * FROM products
WHERE categoryID = 1
ORDER BY productID';
$products = $db->query($query);
A query method with the SELECT statement
as the argument
$products = $db->query('SELECT * FROM products');
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 17
18. A method of the PDO class
for modifying the database
exec($sql_statement)
How to execute an INSERT statement
$category_id = 1;
$code = 'strat';
$name = 'Fender Stratocaster';
$price = 699.99;
$query = "INSERT INTO products
(categoryID, productCode, productName, listPrice)
VALUES
($category_id, '$code', '$name', $price)";
$insert_count = $db->exec($query);
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 18
19. How to execute an UPDATE statement
$product_id = 4;
$price = 599.99;
$query = "UPDATE products
SET listPrice = $price
WHERE productID = $product_id";
$update_count = $db->exec($query);
How to execute a DELETE statement
$product_id = 4;
$query = "DELETE FROM products
WHERE productID = $product_id";
$delete_count = $db->exec($query);
How to display the row counts
<p>Insert count: <?php echo $insert_count; ?></p>
<p>Update count: <?php echo $update_count; ?></p>
<p>Delete count: <?php echo & Associates, Inc.
Murach's PHP and MySQL, C4 © 2010, Mike Murach
$delete_count; ?></p>
Slide 19
20. Getting back to the page layout…
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 20
21. The index.php file (continuing on)
<!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>
<div id="page">
<div id="main">
<h1>Product List</h1>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 21
22. The index.php file (continued)
<div id="sidebar">
<!-- display a list of categories -->
<h2>Categories</h2>
<ul class="nav">
<?php foreach ($categories as $category) : ?>
<li>
<a href="?category_id=
<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 22
23. The index.php file (continued)
<div id="content">
<!-- 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>
<?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>
</div>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 23
24. The index.php file (continued)
</div><!-- end main -->
<div id="footer"></div>
</div><!-- end page -->
</body>
</html>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 24
26. Two of the PHP functions for working with arrays
array()
count($array_name)
How to create an array that with no elements
$rates = array();
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 26
27. How to work with numeric indexes
How to set values
$rates[0] = 5.95; // sets first element
$rates[1] = 10.95; // sets second element
$rates[2] = 15.95; // sets third element
How to get values
$rate = $rates[2]; // gets third element
How to loop through an array with a for loop
for ($i = 0; $i < count($rates); $i++) {
$message .= $rates[$i] . '|';
}
How to loop through an array with a foreach loop
foreach ($rates as $rate) {
$message .= $rate . '|';
}
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 27
28. How to work with string indexes
How to set values
$rates['Ground'] = 5.95;
$rates['2nd Day'] = 10.95;
$rates['Overnight'] = 15.95;
How to get values
$overnight = $rates['Overnight'];
How to loop through an array with a foreach loop
foreach ($rates as $index=>$rate) {
$message .= $index . '='. $rate . ' | ';
}
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 28
29. A method of the PDOStatement class
for getting an array for a row
fetch()
Code that gets a result set that contains one row
$query = 'SELECT productCode, productName, listPrice
FROM products
WHERE productID = $productID';
$products = $db->query($query);
// $products is a PDOStatement object
$product = $products->fetch();
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 29
30. Code that uses a string index to get each column
$product_code = $product['productCode'];
$product_name = $product['productName'];
$product_list_price = $product['listPrice'];
Code that uses a numeric index
to get each column
$product_code = $product[0];
$product_name = $product[1];
$product_list_price = $product[2];
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 30
31. A query method that returns a result set
of two or more rows
$query = 'SELECT productCode, productName, listPrice
FROM products
WHERE categoryID = 1;'
$products = $db->query($query);
// $products contains the result set
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 } ?>
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 31
32. Another syntax for the foreach statement
that works better within PHP tags
<?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 endforeach; ?>
Alternative / shorthand notation…
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 32
34. Homework
• P. 157 of PHP_SQL, Exercise 4-1
– A.) Parts 1 through 4
Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc.
Slide 34
Hinweis der Redaktion Require() : Acts just like the include() function, however, if this function fails, it causes a fatal error that stops the script. DSN : Data Source Name PDO : PHP Data Object. Relatively new to PHP and represents the trend to ENCAPSULATE difficult/complex functions into classes with defined methods. DSN : Data Source Name PDO : PHP Data Object. Relatively new to PHP and represents the trend to ENCAPSULATE difficult/complex functions into simple classes and methods. Require() : Acts just like the include() function, however, if this function fails, it causes a fatal error that stops the script.