How can SQL injection vulnerabilities be prevented when constructing update statements in PHP?

SQL injection vulnerabilities can be prevented when constructing update statements in PHP by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare the SQL update statement with placeholders
$stmt = $pdo->prepare("UPDATE users SET username = :username WHERE id = :id");

// Bind the parameters with user input
$stmt->bindParam(':username', $username);
$stmt->bindParam(':id', $id);

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