How can SQL injection vulnerabilities be avoided when updating user data in a MySQL database using PHP?

SQL injection vulnerabilities can be avoided when updating user data in a MySQL database using PHP by using prepared statements with parameterized queries. This ensures that user input is treated as data rather than executable SQL code, preventing malicious SQL injection attacks.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare a SQL query with placeholders for user input
$stmt = $mysqli->prepare("UPDATE users SET username = ? WHERE id = ?");

// Bind parameters to the placeholders
$stmt->bind_param("si", $newUsername, $userId);

// Set the parameters and execute the query
$newUsername = "newUsername";
$userId = 1;
$stmt->execute();

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