PHP MySQL UPDATE Query

In this source code example, you'll learn how to update the records in a MySQL table using PHP.

PHP MySQL UPDATE Query

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);
 
// Check connection
if ($mysql_connection->connect_errno) {
    printf("connection failed: %s\n", $mysql_connection->connect_error());
    exit();
}
 
// Attempt update query execution
$sql = "UPDATE students SET email='john@mail.com' WHERE id=1";

if(mysqli_query($mysql_connection, $sql)){
    echo "Records were updated successfully.";
} else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}
 
// Close connection
mysqli_close($mysql_connection);
?>
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:

$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysql_connection = mysqli_connect($host, $username, $password, $db_name);
UPDATE SQL query:
// Attempt update query execution
$sql = "UPDATE students SET email='john@mail.com' WHERE id=1";
The mysqli_query() function performs a query against a database:
if(mysqli_query($mysql_connection, $sql)){
    echo "Records were updated successfully.";
} else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysql_connection);
}
Closing MySQL server connection:
// Close connection
mysqli_close($mysql_connection);

Comments