HOWTO · PHP

How to UPDATE Query in a MySQL Table in PHP

The PHP UPDATE query can update existing records in a MySQL table.

On this page

In this tutorial, we will introduce the PHP UPDATE statement. We will explore how you can use this statement to update existing records in a MySQL table.

Use the mysqli_connect to Connect to the Database Containing MySQL Table in PHP

First, we need to understand how to connect to the MySQL table database. See example:

<?php

$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database

$con = mysqli_connect("localhost", $user, $pass, $db);

if ($con->connect_error) {
  die("Connection failed: " . $con->connect_error);

}
// Since the output should be blank for a successful connection you can echo `Database Connected `.
  echo 'Database Connected';
?>

Output:

Database Connected

Our database sample tutorial has a table called parkinglot1. Below is what the table looks like.

CarID BrandName OwnersName RegistrationNumber
1 Benz John KDD125A
2 Porsche Ann KCK345Y
3 Buggatti Loy KDA145Y
4 Audi Maggie KCA678I
5 Filder Joseph KJG998U
6 Tesla Tesla KMH786Y

Let’s assume that the RegistrationNumber for John’s car changed. We will change the registration number from KDD125A to KBK639F.

Use the Update Query to Update Existing Records in a Mysql Table

<?php

$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database

$con = mysqli_connect("localhost", $user, $pass, $db);

if ($con->connect_error) {
  die("Connection failed: " . $con->connect_error);

}
// Since the output should be blank for a sucessful connection you can echo `Database Connected `.
  echo 'Database Connected';
echo '<br>';
  //Update
  $sql = "UPDATE parkinglot1 SET RegistrationNumber = 'KBK639F' WHERE CarID = 1";
// Check if the update was successful.
if ($con->query($sql) === TRUE){
  echo 'Registration Number Updated Successfully';
} else{
  echo 'Error Updating the Registration Number:' . $con->error;
}
?>

Output:

Database Connected
Registration Number Updated Successfully

Here is what our table looks like after the update:

CarID BrandName OwnersName RegistrationNumber
1 Benz John KBK639F
2 Porsche Ann KCK345Y
3 Buggatti Loy KDA145Y
4 Audi Maggie KCA678I
5 Filder Joseph KJG998U
6 Tesla Tesla KMH786Y
Note
You should specify where to make the changes using the WHERE statement as shown in our code; otherwise, you may end up updating everything.