November 28, 2026
How to Update Data in a MySQL Database Using PHP?
You can use the MySQL UPDATE statement to modify or change existing records in a database table using PHP. The UPDATE query allows you to change the values of one or more columns in existing records without inserting new records.
In PHP, you can execute an UPDATE query using the MySQLi library and the mysqli_query() function. You can also use MySQLi prepared statements to update records securely when values are received from HTML forms or user input. The syntax of update query is mentioned below:
Syntax
UPDATE table_name
SET column1=value, column2=value,...
WHERE column_name=value;
The example of Update query is mentioned below:
The following example updates some data in the "Employee" table:
Code
<?php
// Establish database connection
$connection = mysqli_connect("localhost", "marcus", "xyz123", "my_database");
// Check connection
if (!$connection)
{
die("Could not connect with MySQL: " . mysqli_connect_error());
}
// Execute UPDATE query
$sql_query = 'UPDATE Employee SET PhoneNo = "360000" WHERE FirstName = "Edge"';
if (mysqli_query($connection, $sql_query))
{
echo "Record updated successfully.";
}
else
{
echo "Error occurred: " . mysqli_error($connection);
}
// Close database connection
mysqli_close($connection);
?>
FAQ
1. What happens if no records match the WHERE condition in an UPDATE query?
If no records match the specified WHERE condition, MySQL does not modify any records. The query can still execute successfully, but mysqli_affected_rows() will normally return zero.
2. How to update records using values submitted through an HTML form in PHP?
You can collect values from an HTML form using PHP's $_POST or $_GET superglobal arrays and execute an UPDATE query using MySQLi prepared statements.
3. How to prevent SQL injection when updating MySQL records using PHP?
Use MySQLi prepared statements with mysqli_prepare() and mysqli_stmt_bind_param(). These functions separate SQL statements from user-provided values and help prevent SQL injection attacks.