What are the best practices for handling form data in PHP to update database records?

When handling form data in PHP to update database records, it is important to sanitize and validate the input to prevent SQL injection and other security vulnerabilities. It is also crucial to use prepared statements to safely update the database records without exposing them to potential attacks.

// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate form data
    $id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    
    // Update database record using prepared statement
    $stmt = $pdo->prepare("UPDATE table_name SET name = :name WHERE id = :id");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    
    // Redirect to a success page or display a success message
    header("Location: success.php");
    exit();
}