This section describes how to update existing records in database.
If you want to modify existing records in the database, you should write a SQL UPDATE statement,
and send it to the MySQL server for execution with the mysql_query() function.
After that you can call the mysql_affected_rows() function to find out how many records were updated.
The example PHP sctipt below shows you how to update the record of a specified ID value:
<?php #MySQL-Update.php
# Copyright (c) 2007 by Dr. Herong Yang, http://www.herongyang.com/
#
$con = mysql_connect("localhost", "Herong", "TopSecret");
$ok = mysql_select_db("HerongDB", $con);
$sql = "UPDATE Comment SET Name = 'Herong Yang' WHERE ID = 1";
if (mysql_query($sql, $con)) {
print("Number of rows updated: ".mysql_affected_rows()."\n");
} else {
print("SQL statement failed.\n");
print(mysql_errno($con).": ".mysql_error($con)."\n");
}
mysql_close($con);
?>
The output of the script tells us that one record was updated.
To know if the update was done correctly or not, you can run a query to validate.
C:\>\local\php\php MySQL-Update.php
Number of rows updated: 1