Intermediate LevelPHP 8+
How do you implement ACID database transactions in PDO using beginTransaction(), commit(), and rollBack()?
❓ Interview Prompt: Explain PDO transactions, beginTransaction(), commit(), rollBack(), and ensuring atomic database operations.
When executing multi-step database mutations (e.g., deducting funds from Account A and adding funds to Account B), all queries must succeed together or be completely undone. ACID Transactions guarantee atomicity.
PDO Transaction Methods:
1
'$pdo->beginTransaction()': Disables autocommit mode and starts a transaction.
2
'$pdo->commit()': Commits all queries to the database permanently.
3
'$pdo->rollBack()': Cancels all queries executed during the transaction if an exception occurs.
Code Implementation Example
php
<?php
try {
$pdo->beginTransaction();
// Query 1: Deduct funds
$stmt1 = $pdo->prepare("UPDATE accounts SET balance = balance - :amt WHERE id = :src");
$stmt1->execute([':amt' => 100, ':src' => 1]);
// Query 2: Add funds
$stmt2 = $pdo->prepare("UPDATE accounts SET balance = balance + :amt WHERE id = :dst");
$stmt2->execute([':amt' => 100, ':dst' => 2]);
$pdo->commit(); // Atomically save both operations!
} catch (Throwable $e) {
$pdo->rollBack(); // Revert all changes if any query fails!
throw $e;
}💡Executing atomic multi-query database transactions using PDO beginTransaction and rollBack.
🎯 Interview Key Takeaway
Wrap multi-step database updates in PDO beginTransaction() and rollBack() inside try/catch blocks to ensure ACID atomicity.
#PDO#Transactions#ACID#Databases#Intermediate
Back to all PHP 8+ Questions→