What are the best practices for updating specific rows in a MySQL database using PHP?

When updating specific rows in a MySQL database using PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, make sure to properly sanitize and validate user input before updating the database to ensure data integrity. Finally, always handle potential errors that may occur during the update process.

<?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);
}

// Update specific rows in the database
$stmt = $conn->prepare("UPDATE table_name SET column1 = ? WHERE id = ?");
$stmt->bind_param("si", $value1, $id);

// Set parameters and execute
$value1 = "new value";
$id = 1;
$stmt->execute();

// Check for errors
if ($stmt->error) {
    echo "Error: " . $stmt->error;
} else {
    echo "Rows updated successfully";
}

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