What is the correct syntax for updating data in a MySQL database using PHP?
When updating data in a MySQL database using PHP, you need to establish a connection to the database, construct an SQL query with the updated data, and execute the query using PHP's mysqli_query function. Make sure to sanitize user inputs to prevent SQL injection attacks.
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Update data in the database
$id = 1;
$newValue = "New Value";
$sql = "UPDATE table_name SET column_name = '$newValue' WHERE id = $id";
if (mysqli_query($connection, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
// Close connection
mysqli_close($connection);
?>