Here's an example of using the DB module's functions to read our MySQL database. First, you add the support for the DB module using the require statement: require 'DB.php'; . . . Next, you connect using the DB::connect method (recall that you can use :: to indicate what class a method belongs to). Here's how you use this method in general: DB:connect('dbname://username:password@server/databasename); If you're working locally, use localhost as the server. For example, to connect to the produce database locally with the username root with no password, you'd do this: require 'DB.php'; $db = DB::connect('mysql://root:@localhost/produce'); . . . Now you can use the query method of the $db object to execute a SQL query like this one, which reads the entire fruit table: require 'DB.php'; $db = DB::connect('mysql://root:@localhost/produce'); $query = "SELECT * FROM fruit"; $result = $db->query($query); You can recover a row of data using the fetchRow method, as you see in phpdb.php, Example 8-8the DB_FETCHMODE_ASSOC constant makes this method return data as an associative array, so the rest of the code is just as it was with the MySQL functions we used earlier. Example 8-8. Displaying a table with DB, phpdb.php<HTML> <HEAD> <TITLE> Using DB to display a table </TITLE> </HEAD> <BODY> <CENTER> <H1>Using DB to display a table</H1> <?php require 'DB.php'; $db = DB::connect('mysql://root:@localhost/produce'); $query = "SELECT * FROM fruit"; $result = $db->query($query); echo "<TABLE BORDER='1'>"; echo "<TR>"; echo "<TH>Name</TH><TH>Number</TH>"; echo "</TR>"; while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { echo "<TR>"; echo "<TD>", $row['name'], "</TD><TD>", $row['number'], "</TD>"; echo "</TR>"; } echo "</TABLE>"; ?> </CENTER> </BODY> </HTML> The results appear in Figure 8-8. Not bad. Figure 8-8. Using the DB module to display a table. |