Reading from a Database
Now that we can add data to our database, we need to find a way to fetch it. We can extract an individual element from the database with the dba_fetch() function. dba_fetch() requires the name of the element you want to access and a valid DBA resource. The function returns the value you are accessing as a string. So to access the price of the "Tricorder" item, we would use the following code:
$price = dba_fetch( "Tricorder", $dbh );
If the "Tricorder" element does not exist in the database, then dba_fetch() returns false.
You won't always know the names of all the keys in the database, however. What would you do if you needed to output every product and price to the browser without hard-coding the product names into your script? PHP provides a mechanism by which you can loop through every element in a database.
You can get the first key in a database with the dba_firstkey() function. This requires a DBA resource and returns the first key. Note that this won't necessarily be the first element that you added because DBM-like databases often maintain their own ordering systems. After you've retrieved the first key, you can access each subsequent key with the dba_nextkey() function. Once again dba_nextkey() requires a DBA resource and returns an element's key. By combining these functions with dba_fetch(), you can now list an entire database.
Listing 11.3 outputs the products database to the browser. We acquire the first key in the database on line 19 using the dba_firstkey() function. We then use a while loop on line 20 to work our way through all the elements in the database. Elements are acquired with the call to dba_fetch() on line 21. Once we have written the element to the browser we use dba_nextkey() on line 24 to acquire the next key and assign it to the $key variable. When there are no more keys to acquire, dba_nextkey() will return false, and the test expression on line 20 will halt the loop.
Listing 11.3 Reading All Records from a Database
1: <html> 2: <head> 3: <title>Listing 11.3 Reading all 4: records from a Database </title> 5: </head> 6: <body> 7: Here at the Impossible Gadget Shop 8: we're offering the following exciting 9: products: 10: <p> 11: <table border=1 cellpadding ="5"> 12: <tr> 13: <td align="center"> <b>product</b></td> 14: <td align="center"> <b>price</b> </td> 15: </tr> 16: <?php 17: $dbh = dba_open( "./data/products", "c", "gdbm" ) 18: or die( "Couldn't open database" ); 19: $key = dba_firstkey( $dbh ); 20: while ( $key != false ) { 21: $value = dba_fetch( $key, $dbh); 22: print "<tr><td align = \"left\"> $key </td>"; 23: print "<td align = \"right\"> \$$value </td></tr>"; 24: $key = dba_nextkey( $dbh); 25: } 26: dba_close( $dbh ); 27: ?> 28: </table> 29: </body> 30: </html>
Figure 11.1 shows the output from Listing 11.3.
Figure 11.1 Reading all records from a database.