Updating Data into MySQL Database Php | HTML Form

UPDATE statement is used to change or modify existing records in a database table. It is typically used in conjunction with the WHERE clause to change the application to only those records that meet specific criteria.
The basic syntax of the UPDATE statement can be given:

UPDATE table_name SET column1=value, column2=value2,…
WHERE column_name=some_value

Let us use the SQL UPDATE statement’s WHERE clause of a query, after that we will pass through it to the mysql_query () function to update records in a table execute this SQL query. Consider inside the “Demo” database under “people” table:

+———–+————+———–+———————-+
| person_id | first_name | last_name | email_address |
+———–+————+———–+———————-+
| 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 PHP code in the following example update the email address of a person in the persons table whose first_name=’Peter’ and last_name=’Parker’.

Example

<?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_address=’peterparker_new@mail.com’ WHERE first_name=’Peter’ AND last_name=’Parker'”;
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 update the persons table will look something like this:

+———–+————+———–+————————–+
| person_id | first_name | last_name | email_address |
+———–+————+———–+————————–+
| 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 |
+———–+————+———–+————————–+