What are best practices for updating data in a MySQL database using PHP?

When updating data in a MySQL database using PHP, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, it is important to sanitize user input to avoid any unexpected behavior.

<?php
// Establish a connection 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 bind the update statement
$stmt = $conn->prepare("UPDATE table_name SET column1 = ? WHERE id = ?");
$stmt->bind_param("si", $value1, $id);

// Set the values to be updated
$value1 = "new_value";
$id = 1;

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

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