Deleting Data


What about deleting data? Say that the apricot supplier isn't coming through, so you need to remove the entry just added in the previous chunk. As usual, you start by connecting to the 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"); 

Then you can use the SQL DELETE statement to delete the apricots row, which you can identify by name. Here's what it looks like in SQL:

 $query = "DELETE FROM fruit WHERE name = 'apricots'";         .         .         . 

Then you simply execute that new SQL query to delete the apricots row:

 $query = "DELETE FROM fruit WHERE name = 'apricots'"; $result = mysql_query($query)     or die("Query failed: " . mysql_error()); 

After deleting the apricots row, we can display the new version of the fruit table as you see in phpdatadelete.php, Example 8-4.

Example 8-4. Deleting data, phpdatadelete.php
 <HTML>     <HEAD>         <TITLE>             Displaying tables with MySQL         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Displaying tables with MySQL</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 = "DELETE FROM fruit WHERE name = 'apricots'";                  $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> 

You can see the results in Figure 8-4, where the apricots row has indeed been deleted. Now we're able to insert and delete data rows from database tables.

Figure 8-4. Deleting 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