The UPDATE
statement is used to modify existing records in a database table. It is often used with the WHERE
clause to specify which records should be updated based on certain conditions.
The basic syntax of the UPDATE
statement is as follows:
Let's create a SQL query using the UPDATE
statement and the WHERE
clause. After that, we will execute this query by passing it to the PHP mysqli_query()
function to update the records in the table. Consider the persons table within the demo database:
+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 1 | Peter | Parker | peterparker@mail.com | | 2 | John | Rambo | johnrambo@mail.com | | 3 | Clark | Kent | clarkkent@mail.com | | 4 | John | Carter | johncarter@mail.com | | 5 | Harry | Potter | harrypotter@mail.com | +----+------------+-----------+----------------------+
The following PHP example updates the email address of a person in the persons table where the id is equal to 1:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE persons SET email='peterparker_new@mail.com' WHERE id=1";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After updating, the persons table will appear like this:
+----+------------+-----------+--------------------------+
| id | first_name | last_name | email |
+----+------------+-----------+--------------------------+
| 1 | Peter | Parker | peterparker_new@mail.com |
| 2 | John | Rambo | johnrambo@mail.com |
| 3 | Clark | Kent | clarkkent@mail.com |
| 4 | John | Carter | johncarter@mail.com |
| 5 | Harry | Potter | harrypotter@mail.com |
+----+------------+-----------+--------------------------+
Caution: The WHERE
clause in the UPDATE
statement determines which record or records are updated. If omitted, all records in the table will be updated.