When your data changes, it's easy to update your database with the appropriate SQL statement. Here's an examplesay that someone buys a pear, which would change the number of pears in our database from 235 to 234. You can make that change by connecting to MySQL and selecting 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"); Now you can update the value in the pears row of the fruit table like this, where we're setting the value of the number field to 234: $query = "UPDATE fruit SET number = 234 WHERE name = 'pears'"; . . . Then you just execute that query like this: $query = "UPDATE fruit SET number = 234 WHERE name = 'pears'"; $result = mysql_query($query) or die("Query failed: ".mysql_error()); That's all it takes; you can see all this code in phpdataupdate.php, Example 8-2. Example 8-2. Updating database data, phpdataupdate.php<HTML> <HEAD> <TITLE> Updating database data </TITLE> </HEAD> <BODY> <CENTER> <H1>Updating database 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 = "UPDATE fruit SET number = 234 WHERE name = 'pears'"; $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> That's all you need; you can see the results in the fruit table in Figure 8-2, where the number of pears has been updated from 235 to 234. Figure 8-2. Updating data. |