SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Chapter 4

               How to use PHP
           with a MySQL database



Murach's PHP and MySQL, C4    © 2010, Mike Murach & Associates, Inc.
                                                                       Slide 1
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
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
Basic Server Architecture
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
The user interface after the user
       selects a new category




Murach's PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.
                                                                      Slide 6
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
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
The PDO Class

Terms
class
object
argument
PDO object
DSN (Data Source Name)
PDO (PHP Data objects) extension
method




Murach's PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.
                                                                      Slide 9
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
PHP Exception Handling


Terms
exception
exception handling
throw an exception
try/catch statement
try block
catch block
Exception class
PDOException class



Murach's PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.
                                                                      Slide 11
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
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
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
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
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
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
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
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
Getting back to the page layout…




Murach's PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.
                                                                      Slide 20
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
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
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
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
Working with arrays

Terms
array
element
index




 Murach's PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.
                                                                       Slide 25
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
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
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
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
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
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
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
Murach's PHP and MySQL, C4   © 2010, Mike Murach & Associates, Inc.
                                                                      Slide 33
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

Weitere ähnliche Inhalte

Was ist angesagt?

td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 
gDayX - Advanced angularjs
gDayX - Advanced angularjsgDayX - Advanced angularjs
gDayX - Advanced angularjs
gdgvietnam
 
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
Atlassian
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
drubb
 

Was ist angesagt? (18)

Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Knockout js session
Knockout js sessionKnockout js session
Knockout js session
 
Java Web Development with Stripes
Java Web Development with StripesJava Web Development with Stripes
Java Web Development with Stripes
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Knockoutjs
KnockoutjsKnockoutjs
Knockoutjs
 
Stripes Framework
Stripes FrameworkStripes Framework
Stripes Framework
 
gDayX - Advanced angularjs
gDayX - Advanced angularjsgDayX - Advanced angularjs
gDayX - Advanced angularjs
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.js
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2
 
Java script
Java scriptJava script
Java script
 
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
No Coding Necessary: Building User Macros and Dynamic Reports Inside Confluen...
 
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Terrific Frontends
Terrific FrontendsTerrific Frontends
Terrific Frontends
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8
 
Mvc & java script
Mvc & java scriptMvc & java script
Mvc & java script
 

Ähnlich wie Part 2

PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
webhostingguy
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
rani marri
 

Ähnlich wie Part 2 (20)

Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016Coming to Terms with OOP In Drupal - php[world] 2016
Coming to Terms with OOP In Drupal - php[world] 2016
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Phactory
PhactoryPhactory
Phactory
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
OOP Is More Then Cars and Dogs - Midwest PHP 2017
OOP Is More Then Cars and Dogs - Midwest PHP 2017OOP Is More Then Cars and Dogs - Midwest PHP 2017
OOP Is More Then Cars and Dogs - Midwest PHP 2017
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objects
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Fatc
FatcFatc
Fatc
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 

Mehr von A VD

Week 6
Week 6Week 6
Week 6
A VD
 
Part 2
Part 2Part 2
Part 2
A VD
 
Week 5
Week 5Week 5
Week 5
A VD
 
Intro toprogramming part2
Intro toprogramming part2Intro toprogramming part2
Intro toprogramming part2
A VD
 
Week 5
Week 5Week 5
Week 5
A VD
 
Week 4
Week 4Week 4
Week 4
A VD
 
Week 3
Week 3Week 3
Week 3
A VD
 
Week 1
Week 1Week 1
Week 1
A VD
 
Week 2
Week 2Week 2
Week 2
A VD
 

Mehr von A VD (10)

Contest
ContestContest
Contest
 
Week 6
Week 6Week 6
Week 6
 
Part 2
Part 2Part 2
Part 2
 
Week 5
Week 5Week 5
Week 5
 
Intro toprogramming part2
Intro toprogramming part2Intro toprogramming part2
Intro toprogramming part2
 
Week 5
Week 5Week 5
Week 5
 
Week 4
Week 4Week 4
Week 4
 
Week 3
Week 3Week 3
Week 3
 
Week 1
Week 1Week 1
Week 1
 
Week 2
Week 2Week 2
Week 2
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 

Part 2

  • 1. 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
  • 9. The PDO Class Terms class object argument PDO object DSN (Data Source Name) PDO (PHP Data objects) extension method Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 9
  • 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
  • 11. PHP Exception Handling Terms exception exception handling throw an exception try/catch statement try block catch block Exception class PDOException class Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 11
  • 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
  • 25. Working with arrays Terms array element index Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 25
  • 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
  • 33. Murach's PHP and MySQL, C4 © 2010, Mike Murach & Associates, Inc. Slide 33
  • 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

  1. Require() : Acts just like the include() function, however, if this function fails, it causes a fatal error that stops the script.
  2. 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.
  3. 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.
  4. Require() : Acts just like the include() function, however, if this function fails, it causes a fatal error that stops the script.