Inserting New Data


What if you start to carry new stock, such as a new kind of fruit? How can you add a new item to a database table? We'll take a look at this in a new example where we're adding a new type of fruitsay, apricotsto the fruit table. First, we connect to the produce database:

 $connection = mysql_connect("localhost","root","")     or die ("Couldn't connect to server"); $db = mysql_select_db("produce",$connection)     or die ("Couldn't select database"); 

To create a new row for apricots, you can use the SQL INSERT statement like this:

 $query = "INSERT INTO fruit (name, number) VALUES('apricots',     '203')";         .         .         . 

Then you execute this new SQL query to insert the new row:

 $query = "INSERT INTO fruit (name, number) VALUES('apricots',     '203')"; $result = mysql_query($query)     or die("Query failed: " . mysql_error()); 

After the insertion, you can view the new table, as you see in phpdatainsert.php, Example 8-3.

Example 8-3. Inserting new data, phpdatainsert.php
 <HTML>     <HEAD>         <TITLE>             Inserting new data         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Inserting new data</H1>             <?php                  $connection = mysql_connect("localhost","root","")                      or die ("Couldn't connect to server");                  $db = mysql_select_db("produce",$connection)                      or die ("Couldn't select database");                  $query = "INSERT INTO fruit (name, number) VALUES('apricots',                      '203')";                  $result = mysql_query($query)                       or die("Query failed: " . mysql_error());                  $query = "SELECT * FROM fruit";                  $result = mysql_query($query)                       or die("Query failed: " . mysql_error());                  echo "<TABLE BORDER='1'>";                  echo "<TR>";                  echo "<TH>Name</TH><TH>Number</TH>";                  echo "</TR>";                  while ($row = mysql_fetch_array($result))                  {                      echo "<TR>";                      echo "<TD>", $row['name'], "</TD><TD>",                                   $row['number'], "</TD>";                      echo "</TR>";                  }                  echo "</TABLE>";                  mysql_close($connection);              ?>          </CENTER>     </BODY> </HTML> 

The results appear in Figure 8-3complete with apricots. Not bad.

Figure 8-3. Inserting 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