How can PHP developers securely handle user input when updating database records?

When updating database records, PHP developers can securely handle user input by using prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating SQL logic from user input data. By binding parameters to placeholders in the query, developers can ensure that user input is properly sanitized before being executed in the database.

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

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('UPDATE users SET email = :email WHERE id = :id');

// Bind parameters to placeholders
$stmt->bindParam(':email', $email);
$stmt->bindParam(':id', $id);

// Sanitize user input
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);

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