How can SQL syntax errors be avoided when updating values in a MySQL database with PHP?

To avoid SQL syntax errors when updating values in a MySQL database with PHP, it is important to properly escape the values being inserted into the SQL query. This can be done using prepared statements or by using functions like mysqli_real_escape_string() to sanitize the input data.

// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check for connection errors
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Escape the input data to prevent SQL injection
$valueToUpdate = mysqli_real_escape_string($connection, $valueToUpdate);

// Update the value in the database using a prepared statement
$sql = "UPDATE table_name SET column_name = ? WHERE id = ?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, "si", $valueToUpdate, $id);
mysqli_stmt_execute($stmt);

// Close the statement and connection
mysqli_stmt_close($stmt);
mysqli_close($connection);