Updating Data with DB


Here's another oneupdating data with the DB module. As before, we'll reduce the number of pears in the fruit table from 235 to 234. Because we've got a handle on using SQL with the DB module, there's no problem here either; just set up the correct SQL query and then execute that query:

 $query = "UPDATE fruit SET number = 234 WHERE name = 'pears'"; $result = $db->query($query); 

You can see an example of this in Example 8-10, phpdbupdate.php.

Example 8-10. Updating database data, phpdbupdate.php
 <HTML>     <HEAD>         <TITLE>             Using DB to update data         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Using DB to update data</H1>             <?php                 require 'DB.php';                 $db = DB::connect('mysql://root:@localhost/produce');                 $query = "UPDATE fruit SET number = 234 WHERE name = 'pears'";                 $result = $db->query($query);                 $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-10, where we've been able to change the number of pears stored in the database.

Figure 8-10. Using the DB module to update data.


The DB module also includes a DB::isError method to handle errors. Whenever you get a result from a DB module method, you can pass it to the DB::isError method. If that method returns trUE, there was an error, and you can display the appropriate error message with the result object's getMessage method:

 $db = DB::connect('mysql://root:@localhost/produce'); if(DB::isError($db)){     die($db->getMessage()); } 

Now that you can execute SQL statements using the DB module, you have access to most database applicationsall you have to do to select a different type of database server is to change the name of the server type in the connection string.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net