What are some best practices for updating values in a database using PHP?

When updating values in a database using PHP, it is important to properly sanitize user input to prevent SQL injection attacks. It is also recommended to use prepared statements to securely interact with the database. Additionally, always remember to validate the data before updating to ensure data integrity.

<?php
// Assuming $conn is the database connection object

// Sanitize user input
$id = mysqli_real_escape_string($conn, $_POST['id']);
$newValue = mysqli_real_escape_string($conn, $_POST['new_value']);

// Prepare and execute the update statement
$stmt = $conn->prepare("UPDATE table_name SET column_name = ? WHERE id = ?");
$stmt->bind_param("si", $newValue, $id);
$stmt->execute();

// Check if the update was successful
if($stmt->affected_rows > 0){
    echo "Update successful";
} else {
    echo "Update failed";
}

$stmt->close();
$conn->close();
?>