Inserting New Data with DB


What about inserting new data into a table using the DB module, such as the apricots data we added earlier? No problem, just start by connecting to the database using the DB::connect method:

 $db = DB::connect('mysql://root:@localhost/produce');         .         .         . 

We'll use SQL to insert a data row for apricots into the fruit table like this:

 $db = DB::connect('mysql://root:@localhost/produce'); $query = "INSERT INTO fruit (name, number)     VALUES('apricots', '203')";         .         .         . 

And now you can execute this query with the $db->query method:

 $db = DB::connect('mysql://root:@localhost/produce'); $query = "INSERT INTO fruit (name, number)     VALUES('apricots', '203')"; $result = $db->query($query); 

After inserting the new row, we'll display the entire table, as you see in phpdbinsert.php, Example 8-9.

Example 8-9. Inserting database data, phpdbinsert.php
 <HTML>     <HEAD>         <TITLE>             Using DB to insert data         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Using DB to insert data</H1>             <?php                 require 'DB.php';                 $db = DB::connect('mysql://root:@localhost/produce');                 $query = "INSERT INTO fruit (name, number)                     VALUES('apricots', '203')";                 $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-9, where the apricots row has been added, as we wanted.

Figure 8-9. Using the DB module to insert data.




    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