Chapter 4               How to use PHP           with a MySQL databaseMurachs PHP and MySQL, C4    © 2010, Mike Murach & A...
Homework• If you have not installed the Murach databases for  the guitar shop, DO IT ALREADY!• If you are having trouble, ...
future_value.js• Replace some of the repetitive logic with a  function• Lots of ways to do this from the simple to the  co...
Basic Server Architecture
Walk through an example – /book_apps/ch04_product_viewer       The user interfaceMurachs PHP and MySQL, C4   © 2010, Mike ...
The user interface after the user       selects a new categoryMurachs PHP and MySQL, C4   © 2010, Mike Murach & Associates...
The index.php file<?php    require database.php;        // Get category ID        $category_id = $_GET[category_id];      ...
The database.php file<?php    $dsn = mysql:host=localhost;dbname=my_guitar_shop1;    $username = mgs_user;    $password = ...
The PDO ClassTermsclassobjectargumentPDO objectDSN (Data Source Name)PDO (PHP Data objects) extensionmethodMurachs PHP and...
The syntax for creating an object from any class     new ClassName(arguments);The syntax for creating a database objectfro...
PHP Exception HandlingTermsexceptionexception handlingthrow an exceptiontry/catch statementtry blockcatch blockException c...
The syntax for a try/catch statement   try {       // statements that might throw an exception   } catch (ExceptionClass $...
The database.php file (continued)<?php    $dsn = mysql:host=localhost;dbname=my_guitar_shop1;    $username = mgs_user;    ...
The database_error.php file        <!-- the head section -->        <head>            <title>My Guitar Shop</title>       ...
The index.php file (REVISITED)<?php    require database.php;        // Get category ID        $category_id = $_GET[categor...
The index.php file (continued)         // Get products for selected category         $query = "SELECT * FROM products     ...
A method of the PDO classfor executing a SELECT statement    query($select_statement)The syntax for executing a method of ...
A method of the PDO classfor modifying the database      exec($sql_statement)How to execute an INSERT statement      $cate...
How to execute an UPDATE statement  $product_id = 4;  $price = 599.99;  $query = "UPDATE products            SET listPrice...
Getting back to the page layout…Murachs PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.                        ...
The index.php file (continuing on)<!DOCTYPE html><html>    <!-- the head section -->    <head>        <title>My Guitar Sho...
The index.php file (continued)        <div id="sidebar">            <!-- display a list of categories -->            <h2>C...
The index.php file (continued)       <div id="content">           <!-- display a table of products -->           <h2><?php...
The index.php file (continued)                    </div><!-- end main -->                    <div id="footer"></div>    </...
Working with arraysTermsarrayelementindex Murachs PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.              ...
Two of the PHP functions for working with arrays    array()    count($array_name)How to create an array that with no eleme...
How to work with numeric indexes      How to set values      $rates[0] = 5.95;           // sets first element      $rates...
How to work with string indexes    How to set values    $rates[Ground] = 5.95;    $rates[2nd Day] = 10.95;    $rates[Overn...
A method of the PDOStatement classfor getting an array for a row     fetch()Code that gets a result set that contains one ...
Code that uses a string index to get each column      $product_code = $product[productCode];      $product_name = $product...
A query method that returns a result setof two or more rows     $query = SELECT productCode, productName, listPrice       ...
Another syntax for the foreach statementthat works better within PHP tags    <?php foreach ($products as $product) : ?>   ...
Murachs PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.                                                        ...
Homework• P. 157 of PHP_SQL, Exercise 4-1      – A.) Parts 1 through 4Murachs PHP and MySQL, C4   © 2010, Mike Murach & As...
Upcoming SlideShare
Loading in …5
×

Part 2

1,811
-1

Published on

Part 2

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,811
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
33
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • 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.
  • Part 2

    1. 1. Chapter 4 How to use PHP with a MySQL databaseMurachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 1
    2. 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)Murachs PHP and MySQL, C3 © 2010, Mike (or Associates, Inc. Slide 2
    3. 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!Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 3
    4. 4. Basic Server Architecture
    5. 5. Walk through an example – /book_apps/ch04_product_viewer The user interfaceMurachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 5
    6. 6. The user interface after the user selects a new categoryMurachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 6
    7. 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); Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 7
    8. 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(); }?> Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 8
    9. 9. The PDO ClassTermsclassobjectargumentPDO objectDSN (Data Source Name)PDO (PHP Data objects) extensionmethodMurachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 9
    10. 10. The syntax for creating an object from any class new ClassName(arguments);The syntax for creating a database objectfrom 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_nameHow 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); Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 10
    11. 11. PHP Exception HandlingTermsexceptionexception handlingthrow an exceptiontry/catch statementtry blockcatch blockException classPDOException classMurachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 11
    12. 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>"; }Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 12
    13. 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(); }?> Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 13
    14. 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>Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 14
    15. 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. Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 15
    16. 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);?> Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 16
    17. 17. A method of the PDO classfor 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 methodof the database object $PDO_object->query($select_statement)A query method with the SELECT statementin a variable $query = SELECT * FROM products WHERE categoryID = 1 ORDER BY productID; $products = $db->query($query);A query method with the SELECT statementas the argument $products = $db->query(SELECT * FROM products);Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 17
    18. 18. A method of the PDO classfor 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);Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 18
    19. 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.Murachs PHP and MySQL, C4 © 2010, Mike Murach $delete_count; ?></p> Slide 19
    20. 20. Getting back to the page layout…Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 20
    21. 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>Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 21
    22. 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> Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 22
    23. 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>Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 23
    24. 24. The index.php file (continued) </div><!-- end main --> <div id="footer"></div> </div><!-- end page --> </body></html>Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 24
    25. 25. Working with arraysTermsarrayelementindex Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 25
    26. 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();Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 26
    27. 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 . |; }Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 27
    28. 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 . | ; }Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 28
    29. 29. A method of the PDOStatement classfor 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(); Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 29
    30. 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 indexto get each column $product_code = $product[0]; $product_name = $product[1]; $product_list_price = $product[2];Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 30
    31. 31. A query method that returns a result setof two or more rows $query = SELECT productCode, productName, listPrice FROM products WHERE categoryID = 1; $products = $db->query($query); // $products contains the result setHow to use a foreach statement to display theresult 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 } ?> Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 31
    32. 32. Another syntax for the foreach statementthat 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…Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 32
    33. 33. Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 33
    34. 34. Homework• P. 157 of PHP_SQL, Exercise 4-1 – A.) Parts 1 through 4Murachs PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 34
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×