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?"