How can form fields be properly named and handled in PHP to ensure data is correctly passed to the database for updates?

When updating data in a database using PHP, it's important to properly name form fields and handle them in the PHP script to ensure that the data is correctly passed to the database. This involves matching the form field names with the corresponding database columns and sanitizing the input to prevent SQL injection attacks. Additionally, using prepared statements can help prevent SQL injection and ensure data integrity.

// Assuming we have a form with fields named 'name' and 'email' for updating a user's information

// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];

// Sanitize input
$name = htmlspecialchars($name);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Prepare SQL statement using prepared statements
$stmt = $pdo->prepare("UPDATE users SET name = :name, email = :email WHERE id = :id");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':id', $userId);
$stmt->execute();