PDO transactions
A transaction makes several writes of one job succeed or fail together, and PHP drives it through a PDO handle. Every example below runs on SQLite in memory, so the SQL and the output are reproducible on any machine.
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.
<?php $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)"); var_dump($pdo->inTransaction()); echo $pdo->query("SELECT COUNT(*) FROM ledger")->fetchColumn(), PHP_EOL; $pdo->rollBack();
php begin.php
bool(true)
1
The handle reports the open transaction, and the insert is visible to the same connection before anything is committed. The rollback at the end drops it again, which keeps the example clean.
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.
<?php $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 (200)"); $pdo->commit(); echo "saved", PHP_EOL; echo $pdo->query("SELECT COUNT(*) FROM ledger")->fetchColumn(), PHP_EOL; var_dump($pdo->inTransaction());
php commit.php
saved
1
bool(false)
After the commit the row stays, and the handle is back in autocommit mode, which is what the last line shows.
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.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE ledger (id INTEGER PRIMARY KEY, amount INTEGER)"); try { $pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (300)"); throw new Exception("boom"); $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); echo "reverted", PHP_EOL; } echo $pdo->query("SELECT COUNT(*) FROM ledger")->fetchColumn(), PHP_EOL;
php rollback.php
reverted
0
The count of zero is the proof: the insert that ran before the exception is gone with the rollback.
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.
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("PRAGMA busy_timeout = 5000"); echo $pdo->query("PRAGMA busy_timeout")->fetchColumn(), PHP_EOL; var_dump($pdo->inTransaction());
php busy.php
5000
bool(false)
SQLite now waits five seconds for a busy lock instead of failing at once; on MySQL the same idea is a lock wait timeout. No transaction is open at that point, which the second line confirms.
Exercises
- Insert two rows inside one transaction and commit them; count the rows afterwards.
- Throw after the second insert and confirm that the first one is rolled back too.
- Call beginTransaction() twice and catch the exception the second call raises.
- Open a transaction, close the connection without a commit, and open the same file again. SQLite rolls the write back on its own, which is what the quiz question about a forgotten commit checks.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What makes a group of writes atomic?
Answer
A transaction around all of them
The transaction holds the writes together, so the database applies all of them or none.
-
What does
commit()do?Answer
It makes the writes of the open transaction permanent
Commit ends the transaction and keeps everything it wrote; the next statement runs in autocommit mode.
-
What does
rollBack()do to the open transaction?Answer
It discards its writes and ends it
Rollback throws away every write of the transaction, which is why it belongs in the catch arm.
-
Which call tells whether a transaction is open on a PDO handle?
Answer
inTransaction()inTransaction()returns true betweenbeginTransaction()and the commit or the rollback. -
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE ledger (amount INTEGER)"); $pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (100)"); $pdo->rollBack(); echo $pdo->query("SELECT COUNT(*) FROM ledger")->fetchColumn();Answer
0
The rollback removes the insert, so the table is empty when the count runs.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE ledger (amount INTEGER)"); $pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (200)"); $pdo->commit(); $pdo->beginTransaction(); $pdo->exec("INSERT INTO ledger (amount) VALUES (300)"); $pdo->rollBack(); echo $pdo->query("SELECT COUNT(*) FROM ledger")->fetchColumn();Answer
1
The first write is committed and the second one is rolled back, so one row survives.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $pdo->beginTransaction(); $pdo->beginTransaction(); } catch (PDOException $e) { echo $e->getMessage(); }Answer
There is already an active transaction
The second call finds a transaction open and raises a PDOException with exactly that message.
-
What does this program print?
<?php $pdo = new PDO("sqlite::memory:"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); var_dump($pdo->inTransaction()); $pdo->beginTransaction(); $pdo->commit(); var_dump($pdo->inTransaction());Answer
bool(false) / bool(false)
A fresh handle has no transaction, and the commit closes the one that was opened.
-
A script opens a transaction, writes a row and ends without a commit. What does SQLite do with the row?
Answer
It rolls the write back when the connection closes
An open transaction that never commits is rolled back at disconnect; a run that reopens the file counts zero rows.
-
Why is the rollback called inside the
catcharm rather than after the block?Answer
A throw skips the rest of the try block, so the rollback there never runs
The exception jumps out of the try block, so the catch arm is the place that still runs.
The programs on this page were run with PHP 8.5.13 (php -v) on SQLite in memory, with the commands shown above.
Article author: Arthur Isaev