What are some best practices for updating database records using PHP?

When updating database records using PHP, it is important to follow best practices to ensure data integrity and security. One common practice is to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to validate user input and sanitize data before updating the database.

<?php
// Connect to the database
$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);

// Set the values for the update statement
$value1 = "new_value1";
$value2 = "new_value2";
$id = 1;

// Execute the update statement
$stmt->execute();

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