SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Java Web Development with Stripes
Java Web Development with StripesJava Web Development with Stripes
Java Web Development with StripesSamuel Santos
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
gDayX - Advanced angularjs
gDayX - Advanced angularjsgDayX - Advanced angularjs
gDayX - Advanced angularjsgdgvietnam
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.jsMeir Rotstein
 
MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2MVC and Razor - Doc. v1.2
MVC and Razor - Doc. v1.2Naji El Kotob
 
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...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 ...
No Coding Necessary: Building Confluence User Macros Cheat Sheet - Atlassian ...Atlassian
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Themingdrubb
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8John Doyle
 
Mvc & java script
Mvc & java scriptMvc & java script
Mvc & java scriptEyal Vardi
 

La actualidad más candente (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
 

Similar a Part 2

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] 2016Chris Tankersley
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
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 @codelytvCodelyTV
 
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 gtk2Elizabeth Smith
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
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 2017Chris Tankersley
 
Introducing PHP Data Objects
Introducing PHP Data ObjectsIntroducing PHP Data Objects
Introducing PHP Data Objectswebhostingguy
 
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 CodeSWIFTotter Solutions
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For BeginnersPriti Solanki
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptxrani marri
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
 

Similar a 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
 

Más de A VD

Contest
ContestContest
ContestA VD
 
Week 6
Week 6Week 6
Week 6A VD
 
Part 2
Part 2Part 2
Part 2A VD
 
Week 5
Week 5Week 5
Week 5A VD
 
Intro toprogramming part2
Intro toprogramming part2Intro toprogramming part2
Intro toprogramming part2A VD
 
Week 5
Week 5Week 5
Week 5A VD
 
Week 4
Week 4Week 4
Week 4A VD
 
Week 3
Week 3Week 3
Week 3A VD
 
Week 1
Week 1Week 1
Week 1A VD
 
Week 2
Week 2Week 2
Week 2A VD
 

Más de 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
 

Último

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Último (20)

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

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

Notas del editor

  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.