PDO transactions

beginTransaction

A transaction groups several writes into one atomic unit. Either all changes land together or none of them land at all.

Start the block first, then run the inserts and updates that must stay consistent.

$pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE ledger (id INTEGER PRIMARY KEY, amount INTEGER)"); $pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (100)");

Commit

Commit makes all grouped writes permanent at once. Call it only after every step inside the block has succeeded.

After commit other connections can see the new rows, and the next transaction can begin cleanly.

$pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (200)"); $pdo->commit(); echo "saved";

Rollback on catch

Any error inside the block should undo the partial work. Wrap the steps in try catch and roll back on failure.

This pattern keeps money totals, stock counts, and related tables in agreement.

try { $pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (300)"); throw new Exception("boom"); $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); echo "reverted"; }

Isolation note

Parallel connections may compete for the same rows while a transaction is open. Short transactions lower the chance of busy locks and retries.

Keep user input and network calls outside the block, and write only the minimal set of queries inside.

$pdo->exec("PRAGMA busy_timeout = 5000"); var_dump($pdo->inTransaction());

Next: PDO fetch modes

Article author: Arthur Isaev