How can SQL injections be prevented when updating database records in PHP?

SQL injections can be prevented when updating database records in PHP by using prepared statements with parameterized queries. This method separates the SQL query from the user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database engine knows how to treat the input data as data rather than executable code.

// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

// Prepare and bind SQL statement
$stmt = $conn->prepare("UPDATE table_name SET column_name = ? WHERE id = ?");
$stmt->bind_param("si", $value, $id);

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

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