What best practices should be followed when updating database records using PHP scripts to ensure data integrity and consistency?

When updating database records using PHP scripts, it is important to follow best practices to ensure data integrity and consistency. This includes using prepared statements to prevent SQL injection attacks, validating user input to avoid errors, and implementing proper error handling to handle any issues that may arise during the update process.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and execute the update statement
$stmt = $conn->prepare("UPDATE table_name SET column1 = ?, column2 = ? WHERE id = ?");
$stmt->bind_param("ssi", $value1, $value2, $id);

$value1 = "new_value1";
$value2 = "new_value2";
$id = 1;

$stmt->execute();

// Check for errors
if ($stmt->affected_rows > 0) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

// Close the statement and connection
$stmt->close();
$conn->close();
?>