How can PHP be used to securely handle user input for updating specific variables in a document?

When updating specific variables in a document based on user input, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or XSS attacks. One way to securely handle user input in PHP is to use functions like htmlspecialchars() to prevent XSS attacks and prepared statements or parameterized queries to prevent SQL injection.

// Assuming $userInput contains the user input for updating a specific variable in a document

// Sanitize the user input to prevent XSS attacks
$sanitizedInput = htmlspecialchars($userInput);

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("UPDATE documents SET specific_variable = :input WHERE id = :id");
$stmt->bindParam(':input', $sanitizedInput);
$stmt->bindParam(':id', $documentId);
$stmt->execute();