Transaction management in PHP - Time & Space Complexity
When managing transactions in PHP, it's important to know how the time to complete operations changes as the number of database actions grows.
We want to understand how the time cost increases when handling multiple queries inside a transaction.
Analyze the time complexity of the following code snippet.
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO orders (product_id, quantity) VALUES (?, ?)');
foreach ($items as $item) {
$stmt->execute([$item['id'], $item['qty']]);
}
$pdo->commit();
This code starts a transaction, inserts multiple order items one by one, then commits the transaction.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Executing the prepared SQL insert inside the loop.
- How many times: Once for each item in the input array.
Each additional item adds one more database insert operation inside the transaction.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 insert executions |
| 100 | 100 insert executions |
| 1000 | 1000 insert executions |
Pattern observation: The total operations grow directly in proportion to the number of items.
Time Complexity: O(n)
This means the time to complete the transaction grows linearly with the number of items processed.
[X] Wrong: "Starting a transaction makes the whole process constant time regardless of item count."
[OK] Correct: The transaction groups operations but each insert still runs separately, so time grows with item count.
Understanding how transaction time grows helps you explain database efficiency and write better code that scales well.
"What if we batch all inserts into a single query inside the transaction? How would the time complexity change?"
Practice
beginTransaction() in PHP when working with databases?Solution
Step 1: Understand the role of
This function starts a transaction, grouping multiple database changes into one unit.beginTransaction()Step 2: Recognize transaction benefits
It allows committing all changes at once or rolling back if something goes wrong, ensuring data integrity.Final Answer:
To start a group of database operations that can be committed or rolled back together -> Option AQuick Check:
beginTransaction() starts a transaction [OK]
- Thinking it saves changes immediately
- Confusing it with closing the connection
- Assuming it checks database availability
Solution
Step 1: Recall PDO commit method
The correct method to save all changes in a transaction iscommit()called on the PDO object.Step 2: Check method names
Only$pdo->commit();matches the correct PDO syntax; others are invalid method names.Final Answer:
$pdo->commit(); -> Option DQuick Check:
commit() saves transaction changes [OK]
- Using incorrect method names like commitTransaction()
- Trying to call commit as a function with argument
- Confusing commit with rollback
$pdo->beginTransaction();
$pdo->exec("INSERT INTO users (name) VALUES ('Alice')");
$pdo->rollBack();
echo $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();Solution
Step 1: Analyze transaction commands
The code starts a transaction, inserts a user, then rolls back, undoing the insert.Step 2: Check final data count
Since the insert was rolled back, the users table remains unchanged, so count is 0.Final Answer:
0 -> Option AQuick Check:
rollBack() undoes insert, count = 0 [OK]
- Assuming insert stays after rollBack()
- Confusing commit() with rollBack()
- Expecting syntax or runtime error
try {
$pdo->beginTransaction();
$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->commit();
}Solution
Step 1: Review transaction error handling
In case of error, changes should be undone withrollBack(), not committed.Step 2: Identify catch block mistake
The catch block incorrectly callscommit(), which saves partial or faulty changes.Final Answer:
Using commit() in catch block instead of rollBack() -> Option BQuick Check:
Errors need rollBack(), not commit() [OK]
- Calling commit() in catch block
- Forgetting to handle exceptions
- Confusing exec() and query() methods
Solution
Step 1: Understand transaction grouping
All related updates must be inside the transaction to ensure atomicity.Step 2: Check step order
Starting with beginTransaction(), then updating both accounts, and finally committing ensures either all changes apply or none.Final Answer:
Begin transaction, update sender balance, update receiver balance, commit transaction -> Option CQuick Check:
All DB changes inside transaction before commit [OK]
- Updating before starting transaction
- Committing too early before all updates
- Not grouping all changes inside transaction
Ready to prove it?
Pass the test and this pattern moves unknown
