Page 400 - Beginning PHP 5.3
P. 400

Part III: Using PHP in Practice

              Try It Out     Read a Database Table with PHP
                This simple example shows you how to use PDO to connect to a MySQL server and database, read all
                the rows of a table, and handle any errors that might occur.
                First, you need a database and table to work with. This example assumes that you’ve already created
                the database called mydatabase, and created and populated the table called fruit, as shown in
                previous sections. If you haven’t, you can easily re-create the database and table by typing the
                following into the MySQL command-line tool:
                    CREATE DATABASE mydatabase;
                    USE mydatabase;

                    CREATE TABLE fruit (
                      id          SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
                      name        VARCHAR(30) NOT NULL,
                      color       VARCHAR(30) NOT NULL,
                      PRIMARY KEY (id)
                    );

                    INSERT INTO fruit ( name, color ) VALUES ( ‘banana’, ‘yellow’ );
                    INSERT INTO fruit ( name, color ) VALUES ( ’tangerine’, ‘orange’ );
                    INSERT INTO fruit ( name, color ) VALUES ( ‘plum’, ‘purple’ );
                Now save the following script as get_fruit.php in your document root folder, replacing mypass
                with the password you set for the root user in MySQL, and run the script in your Web browser. You
                should see a result similar to Figure 12-1.

                    <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
                      “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
                    <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
                      <head>
                        <title>Fruit</title>
                        <link rel=”stylesheet” type=”text/css” href=”common.css” />
                      </head>
                      <body>

                        <h1>Fruit</h1>

                    <?php
                    $dsn = “mysql:dbname=mydatabase”;
                    $username = “root”;
                    $password = “mypass”;

                    try {
                      $conn = new PDO( $dsn, $username, $password );
                      $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                    } catch ( PDOException $e ) {








              362





                                                                                                      9/21/09   9:11:15 AM
          c12.indd   362
          c12.indd   362                                                                              9/21/09   9:11:15 AM
   395   396   397   398   399   400   401   402   403   404   405