What is the best practice for updating database fields in PHP?

When updating database fields in PHP, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data integrity. Prepared statements separate SQL logic from user input, making it safer to execute queries with user-provided data.

// 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 bind the update statement
$stmt = $conn->prepare("UPDATE table_name SET column_name = ? WHERE id = ?");
$stmt->bind_param("si", $column_value, $id);

// Set the values for the parameters
$column_value = "new_value";
$id = 1;

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

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