Transactions
On this page
What a Transaction Is
A transaction groups multiple queries into a single atomic unit: either all succeed or all fail. This prevents partial updates and data corruption.
When You Need Transactions
Use transactions when multiple tables/rows must stay consistent: payment records, inventory updates, logging + main write, or moving money between accounts.
Basic Transaction Example
Wrap related queries in beginTransaction() / commit(). On error, rollback.
<?php
try {
$pdo->beginTransaction();
$stmt1 = $pdo->prepare("INSERT INTO orders (user_id, total) VALUES (?, ?)");
$stmt1->execute([1, 144.00]);
$orderId = (int)$pdo->lastInsertId();
$stmt2 = $pdo->prepare("INSERT INTO order_items (order_id, sku, qty) VALUES (?, ?, ?)");
$stmt2->execute([$orderId, "SKU-123", 2]);
$pdo->commit();
echo "OK";
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
// log $e in production
echo "Failed";
}
Transaction Gotchas
Do not keep transactions open too long (slow requests, external API calls). Keep the transaction scope minimal: validate first, then open transaction, run queries, commit.
Production Tip
Transactions are a correctness tool. Use them whenever partial writes would break invariants. Combine with proper indexes and short transaction windows to avoid lock contention.