PHP › PDO & Databases
How do database transactions work in PDO, and why are they important for ensuring multiple related database operations either all succeed together or all fail together?
IntermediateAnswer
A transaction lets you group multiple database operations together so that they are treated as a single atomic unit, meaning either every operation within the transaction succeeds and is permanently committed, or if any operation fails, the entire transaction can be rolled back, undoing every change made so far, which is essential for operations like transferring money between two accounts, where you never want one account to be debited without the corresponding credit also succeeding.
$pdo->beginTransaction();
try {
$pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
$pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}Real-world example A banking application wraps a fund transfer between two accounts in a transaction, ensuring that if the second update somehow fails after the first one succeeds, the entire operation rolls back completely, guaranteeing the total money in the system always remains correctly balanced.