What are the common errors and solutions when updating user profiles in PHP using SQL queries with variables?

One common error when updating user profiles in PHP using SQL queries with variables is not properly sanitizing user input, which can lead to SQL injection attacks. To solve this, use prepared statements with bound parameters to securely update user profiles.

// Assuming $conn is the database connection

// Sanitize user input
$user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
$new_username = mysqli_real_escape_string($conn, $_POST['new_username']);
$new_email = mysqli_real_escape_string($conn, $_POST['new_email']);

// Update user profile using prepared statement
$stmt = $conn->prepare("UPDATE users SET username = ?, email = ? WHERE id = ?");
$stmt->bind_param("ssi", $new_username, $new_email, $user_id);
$stmt->execute();

// Check if update was successful
if ($stmt->affected_rows > 0) {
    echo "User profile updated successfully";
} else {
    echo "Failed to update user profile";
}

$stmt->close();
$conn->close();