How can the code structure be improved to handle multiple database updates more efficiently in PHP?
To handle multiple database updates more efficiently in PHP, you can use transactions to ensure that all updates are either committed or rolled back together. This helps maintain data integrity and prevents partial updates in case of errors.
// Start a transaction
$pdo->beginTransaction();
try {
// Perform multiple database updates
$stmt1 = $pdo->prepare("UPDATE table1 SET column1 = :value1 WHERE id = :id");
$stmt1->execute(['value1' => 'new_value1', 'id' => 1]);
$stmt2 = $pdo->prepare("UPDATE table2 SET column2 = :value2 WHERE id = :id");
$stmt2->execute(['value2' => 'new_value2', 'id' => 2]);
// Commit the transaction if all updates are successful
$pdo->commit();
} catch (Exception $e) {
// Roll back the transaction if an error occurs
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage();
}