How can you handle form submissions in PHP when dealing with multiple database entries to ensure that each entry is updated correctly?

When handling form submissions in PHP with multiple database entries, it is important to use transactions to ensure that all entries are updated correctly. By starting a transaction, you can execute multiple queries and commit them all at once if there are no errors. This helps maintain data integrity and prevents partial updates.

<?php

// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $pdo->beginTransaction();

    // Update multiple entries in the database
    $stmt1 = $pdo->prepare("UPDATE table1 SET column1 = :value1 WHERE id = :id1");
    $stmt2 = $pdo->prepare("UPDATE table2 SET column2 = :value2 WHERE id = :id2");

    $stmt1->execute(array(':value1' => 'new_value1', ':id1' => 1));
    $stmt2->execute(array(':value2' => 'new_value2', ':id2' => 2));

    $pdo->commit();
    echo "All entries updated successfully!";
} catch (PDOException $e) {
    $pdo->rollBack();
    echo "Error updating entries: " . $e->getMessage();
}