Explain it simply
Explain it simply
Imagine moving money between two jars: take 30 out of jar A and put 30 into jar B. If the phone rings after you took the money out of A, the money is still in your hand and in neither jar. A transaction is the promise that both steps happen or neither does.
PDO is PHP's common tool for talking to databases, and prepared statements are how you hand it values safely. This lesson puts the two together. Whenever several changes belong together, the transaction is what keeps anyone from ever seeing them half done.
Problem → Why → Solution
The problem: when the second statement fails, the first one stays
A transfer script runs two UPDATE statements one after the other. It works every day until the second one fails: the receiving account was already deleted, the database connection dropped, or a rule such as "a balance may never be negative" rejects the change. The first UPDATE has already happened and nothing undoes it.
Worse, even when the error is caught the page just says "Failed" and nobody notices that the data is now wrong. When the total money goes from 150 to 230, it is very hard to find out where the extra 80 came from.
<?php
// Two separate statements with no transaction around them.
$pdo->exec("UPDATE accounts SET balance = balance + 80 WHERE owner = 'alice'");
$pdo->exec("UPDATE accounts SET balance = balance - 80 WHERE owner = 'bob'");
// bob only has 50. If this second statement fails, alice's +80 stays behind.Why does the first UPDATE stay behind?
By default the database runs in autocommit mode, where every single statement is its own tiny transaction. The first UPDATE is committed the moment it finishes, so the database cannot know that the second statement belongs with it. Only you know the two statements are one business action, and you tell the database by wrapping them in a transaction.
Core concept: PDO, prepared statements and transactions
PDO (PHP Data Objects) gives you one API for MySQL, SQLite, PostgreSQL and other databases; only the connection string (the DSN) differs. With the error mode set to PDO::ERRMODE_EXCEPTION, every failing SQL statement throws a PDOException. That has been the default since PHP 8.0, but writing it explicitly makes the code easier to read. With a prepared statement the SQL goes first with placeholders and the values follow separately, so a value can never be re-read as SQL.
1. beginTransaction()
Autocommit is switched off. From now on your statements are a draft that only your own connection can see.
2. Run the dependent statements
Run each statement as a prepared statement. Throw when the rowCount() is not what you expected, otherwise a statement that did nothing will be committed silently.
3. commit()
Every change in the draft becomes permanent at once, and other connections can finally see it.
4. rollBack() in the catch block
Everything done since beginTransaction() is thrown away. Then rethrow the exception so the calling code knows that something went wrong.
| Tool | Protects against | Lives in |
|---|---|---|
| Prepared statement | SQL injection | PHP and the driver |
| Transaction | Half-applied multi-step changes | The database |
| CHECK / UNIQUE / NOT NULL | Invalid or duplicate data | The database schema |
PHP validation is the first line of defence and gives the user a friendly message. Constraints are the second line. Think of the three tools as layers: prepared statements keep the SQL honest, the transaction keeps the sequence honest, and the constraints keep the data honest. A bug, another script, an admin typing SQL by hand, or two requests arriving at the same moment can get around a PHP check, but never around a rule that the database itself enforces.
- beginTransaction() opens a draft
- Run every dependent statement
- commit() if all succeeded
- rollBack() if anything threw
A rollback undoes changes inside the database only. It cannot undo PHP variables or an email that was already sent.
General pattern
<?php
$db->beginTransaction();
try {
$first->execute($firstValues);
$second->execute($secondValues);
$db->commit();
} catch (Throwable $error) {
$db->rollBack();
throw $error;
}The transaction is opened outside the try. Inside it the statements run and commit() comes last; if anything fails, the catch block calls rollBack() and rethrows the exception.
Transfer money with and without a transaction
In this script the accounts table has CHECK (balance >= 0) and a UNIQUE owner. alice holds 100 and bob holds 50, so the total is 150. The two transfer functions run the statements in the same order (credit the receiver first, debit the sender second); the only difference is that transferSafe() uses a transaction. When bob tries to send 80, the debit breaks the CHECK rule and fails.
<?php
declare(strict_types=1);
function freshBank(): PDO
{
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
owner TEXT NOT NULL UNIQUE,
balance INTEGER NOT NULL CHECK (balance >= 0)
)');
$pdo->exec("INSERT INTO accounts (owner, balance) VALUES
('alice', 100), ('bob', 50)");
return $pdo;
}
function show(PDO $pdo, string $label): void
{
$parts = [];
$total = 0;
foreach ($pdo->query('SELECT owner, balance FROM accounts ORDER BY owner') as $row) {
$parts[] = "{$row['owner']}={$row['balance']}";
$total += $row['balance'];
}
echo str_pad($label, 24) . implode(' ', $parts) . " total=$total\n";
}
function adjust(PDO $pdo, string $owner, int $delta): void
{
$stmt = $pdo->prepare(
'UPDATE accounts SET balance = balance + :delta WHERE owner = :owner'
);
$stmt->execute(['delta' => $delta, 'owner' => $owner]);
if ($stmt->rowCount() !== 1) {
throw new RuntimeException("No account named $owner");
}
}
// Credit first, then debit, so a failing debit leaves the credit behind.
function transferUnsafe(PDO $pdo, string $from, string $to, int $amount): void
{
adjust($pdo, $to, $amount);
adjust($pdo, $from, -$amount);
}
function transferSafe(PDO $pdo, string $from, string $to, int $amount): void
{
$pdo->beginTransaction();
try {
adjust($pdo, $to, $amount);
adjust($pdo, $from, -$amount);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
}
// 1) No transaction: bob only has 50, so the debit of 80 breaks the CHECK rule.
$pdo = freshBank();
show($pdo, 'start:');
try {
transferUnsafe($pdo, 'bob', 'alice', 80);
} catch (Throwable $e) {
echo 'unsafe transfer failed (' . get_class($e) . ")\n";
}
show($pdo, 'after unsafe:');
// 2) Same failing transfer inside a transaction: the credit is undone.
$pdo = freshBank();
try {
transferSafe($pdo, 'bob', 'alice', 80);
} catch (Throwable $e) {
echo 'safe transfer failed (' . get_class($e) . ")\n";
}
show($pdo, 'after safe failure:');
// 3) A transfer that is allowed commits both changes.
transferSafe($pdo, 'alice', 'bob', 30);
show($pdo, 'after safe success:');
// 4) A missing account is caught by our own check, and also rolls back.
try {
transferSafe($pdo, 'carol', 'alice', 10);
} catch (RuntimeException $e) {
echo 'rejected: ' . $e->getMessage() . "\n";
}
show($pdo, 'after missing account:');Code breakdown
- A rule inside the schema
balance INTEGER NOT NULL CHECK (balance >= 0)This rule lives in the table itself, not in PHP, so no script, whoever wrote it, can make a balance negative.
- Fail on a surprising row count
if ($stmt->rowCount() !== 1) {adjust() should change exactly one account. If nothing changed (the account does not exist) it throws a RuntimeException, so a name like "carol" cannot be skipped silently.
- Open the draft
$pdo->beginTransaction();From this line on, until commit() or rollBack() is called, the changes are only provisional.
- Make both changes permanent together
$pdo->commit();This line is reached only if both statements succeeded, which is why "after safe success" shows alice=70 bob=80 with the total still at 150.
- Undo and tell the caller
$pdo->rollBack();When the debit fails, the credit to alice is undone as well. Then throw $e passes the error to the caller, which is why "after safe failure" shows 100 and 50 again.
start: alice=100 bob=50 total=150
unsafe transfer failed (PDOException)
after unsafe: alice=180 bob=50 total=230
safe transfer failed (PDOException)
after safe failure: alice=100 bob=50 total=150
after safe success: alice=70 bob=80 total=150
rejected: No account named carol
after missing account: alice=70 bob=80 total=150Prepared statements side by side
The script below sends the text "nobody@example.com' OR '1'='1" in two ways. With string concatenation the quote becomes a new condition inside the SQL, so both rows come back. With a placeholder the whole text is compared as one email value, so nothing matches. The last lines show positional ? placeholders. Do not mix named (:email) and positional (?) placeholders in the same statement.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL,
is_admin INTEGER NOT NULL
)');
$pdo->exec("INSERT INTO users (email, is_admin) VALUES
('aung@example.com', 0), ('root@example.com', 1)");
$input = "nobody@example.com' OR '1'='1";
// Wrong: the input becomes part of the SQL text.
$sql = "SELECT email FROM users WHERE email = '$input' ORDER BY id";
echo "Concatenated: " . count($pdo->query($sql)->fetchAll()) . " row(s) match\n";
// Right: the input travels separately and is only ever treated as a value.
$stmt = $pdo->prepare('SELECT email FROM users WHERE email = :email ORDER BY id');
$stmt->execute(['email' => $input]);
echo "Prepared: " . count($stmt->fetchAll()) . " row(s) match\n";
// Positional placeholders do the same job.
$sql = 'SELECT email FROM users WHERE is_admin = ? AND email LIKE ? ORDER BY id';
$stmt = $pdo->prepare($sql);
$stmt->execute([1, 'root@%']);
echo "Positional: " . $stmt->fetchColumn() . "\n";Concatenated: 2 row(s) match
Prepared: 0 row(s) match
Positional: root@example.comConstraints: the second line of defence
This demo breaks each of the three constraints in turn. UNIQUE refuses a repeated email, CHECK refuses an age under 13 and NOT NULL refuses a row with no email. Each failure raises one PDOException and stores nothing. SQLSTATE 23000 is the standard code for an integrity constraint violation, and both MySQL and SQLite report constraint failures with it.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE members (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
age INTEGER NOT NULL CHECK (age >= 13)
)');
$insert = $pdo->prepare('INSERT INTO members (email, age) VALUES (:email, :age)');
$attempts = [
'valid row' => ['email' => 'su@example.com', 'age' => 20],
'duplicate email' => ['email' => 'su@example.com', 'age' => 21],
'age too low' => ['email' => 'kid@example.com', 'age' => 9],
'missing email' => ['email' => null, 'age' => 30],
];
foreach ($attempts as $label => $row) {
try {
$insert->execute($row);
echo str_pad($label, 16) . "stored\n";
} catch (PDOException $e) {
echo str_pad($label, 16) . "refused, SQLSTATE " . $e->getCode() . "\n";
}
}
$count = $pdo->query('SELECT COUNT(*) FROM members')->fetchColumn();
echo "Rows in table: $count\n";valid row stored
duplicate email refused, SQLSTATE 23000
age too low refused, SQLSTATE 23000
missing email refused, SQLSTATE 23000
Rows in table: 1CHECK on MySQL
MySQL enforces CHECK constraints only from version 8.0.16; earlier versions accept the syntax and ignore it. This lesson's demos run on SQLite, so check your own MySQL server's version and manual.
Misusing the transaction API, and a helper
PDO throws a PDOException when you call rollBack() while no transaction is active, or call beginTransaction() while one is already open. That is why the catch block should check inTransaction() before calling rollBack(): on MySQL, for example, a DDL statement can commit implicitly and leave no transaction behind. The first script below shows both errors.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$pdo->rollBack();
} catch (PDOException $e) {
echo "rollBack: " . $e->getMessage() . "\n";
}
$pdo->beginTransaction();
try {
$pdo->beginTransaction();
} catch (PDOException $e) {
echo "nested begin: " . $e->getMessage() . "\n";
}
echo 'still inside a transaction? ' . var_export($pdo->inTransaction(), true) . "\n";
$pdo->commit();
echo 'after commit: ' . var_export($pdo->inTransaction(), true) . "\n";rollBack: There is no active transaction
nested begin: There is already an active transaction
still inside a transaction? true
after commit: falseTo avoid repeating this boilerplate, write an atomic() helper that takes a plain callback and runs it inside a transaction. The finally block runs whether the work succeeds or fails, which makes it the right place for logging or timing. In the demo the second batch contains a duplicate 'a', which breaks UNIQUE, and d and e are discarded along with it.
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE log (id INTEGER PRIMARY KEY, line TEXT NOT NULL UNIQUE)');
function atomic(PDO $pdo, callable $work): mixed
{
$pdo->beginTransaction();
try {
$result = $work($pdo);
$pdo->commit();
return $result;
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
} finally {
$open = var_export($pdo->inTransaction(), true);
echo "[atomic] finished, still in a transaction: $open\n";
}
}
function addLines(PDO $pdo, array $lines): int
{
$stmt = $pdo->prepare('INSERT INTO log (line) VALUES (:line)');
foreach ($lines as $line) {
$stmt->execute(['line' => $line]);
}
return count($lines);
}
$stored = atomic($pdo, fn (PDO $db) => addLines($db, ['a', 'b', 'c']));
echo "Stored $stored lines\n";
try {
// 'a' is a duplicate, so the whole batch must be refused
atomic($pdo, fn (PDO $db) => addLines($db, ['d', 'e', 'a']));
} catch (PDOException $e) {
echo "Batch refused, nothing from it was kept\n";
}
$count = $pdo->query('SELECT COUNT(*) FROM log')->fetchColumn();
echo "Rows now: $count\n";[atomic] finished, still in a transaction: false
Stored 3 lines
[atomic] finished, still in a transaction: false
Batch refused, nothing from it was kept
Rows now: 3What changes on MySQL
All the runnable code in this lesson runs on SQLite. There is no MySQL server here, so I cannot show MySQL output. The PDO code stays the same, though, and the differences are listed below. The snippet is the shape of a MySQL connection and table; it needs a MySQL server, so it is not run here.
<?php
// MySQL only. Host, database and credentials are placeholders.
$pdo = new PDO(
'mysql:host=localhost;dbname=thutatech_demo;charset=utf8mb4',
'app_user',
'secret',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false, // use real server-side prepares
]
);
// Tables that take part in a transaction must use a transactional engine.
$pdo->exec('CREATE TABLE accounts (
id INT AUTO_INCREMENT PRIMARY KEY,
owner VARCHAR(50) NOT NULL UNIQUE,
balance INT NOT NULL,
CHECK (balance >= 0)
) ENGINE=InnoDB');- DSN: it looks like mysql:host=...;dbname=...;charset=utf8mb4 and replaces sqlite::memory:.
- Engine: transactions work only on a transactional engine such as InnoDB; MyISAM ignores them.
- DDL: on MySQL, CREATE/ALTER/DROP TABLE commits implicitly. On SQLite even DDL can be rolled back.
- Deadlocks: when two transactions collide, MySQL may abort one of them with a deadlock error; the usual remedy is to run the transaction again.
- Auto-increment ids: MySQL (InnoDB) does not hand a rolled-back id number back, so ids can have gaps.
In real projects
In real projects
An online shop puts everything that belongs to one order in a single transaction: reducing stock, inserting the order row, writing the payment record and an audit log line. If any step fails, all of it is undone and no stock disappears. Registering a user works the same way when it creates a users row, a profile row and default settings together. When importing a CSV, one bad line out of 1,000 rolls back the whole import so you can fix the file and upload it again.
Keep transactions short. While a transaction is open the database may hold locks on rows, so do not call another website, send email or sleep inside it. Send the email after commit() has returned, because a rollback cannot take back a message that has already left.
Common mistakes
Common mistakes
Swallowing the exception without rolling back
If the catch block only echoes 'failed' and never calls rollBack(), the transaction stays open and later statements can end up inside it. PDO rolls back an unfinished transaction when the script ends, but do not rely on waiting for that.
Committing without checking rowCount()
An UPDATE that matches nothing changes 0 rows without raising an error. If such a statement sits in a transaction and you never check rowCount(), the credit side can succeed while the debit side did nothing, and the whole thing is still committed.
Putting things that cannot be undone inside
Sending an email, calling a payment gateway or writing a file cannot be undone by rollBack(). Keep only database changes inside the transaction and do the rest after the commit.
Putting the catch blocks in the wrong order
PDOException extends RuntimeException. If catch (RuntimeException) comes before catch (PDOException), the first block swallows every PDO error. Put the more specific class first.
Mini challenge
Place an order inside a transaction
Write placeOrder(PDO $pdo, string $sku, int $qty): string. It must insert an order row and reduce the stock, both inside one transaction. When the stock is too low (the CHECK rule breaks) or the sku does not exist, undo the order row as well and return a line that explains why.
- Return a refusal line without touching the database when qty <= 0
- Run the order insert and the stock UPDATE between beginTransaction() and commit()
- Check the UPDATE's rowCount() and throw when the sku does not exist
- Return different lines for a PDOException (too little stock) and an unknown sku, and call rollBack() in both cases
<?php
declare(strict_types=1);
// $pdo already has:
// stock(sku TEXT PRIMARY KEY, qty INTEGER CHECK (qty >= 0))
// orders(id INTEGER PRIMARY KEY, sku TEXT, qty INTEGER CHECK (qty > 0))
function placeOrder(PDO $pdo, string $sku, int $qty): string
{
// TODO: refuse qty <= 0 before any SQL runs
// TODO: beginTransaction(), then INSERT the order row
// TODO: UPDATE stock SET qty = qty - :qty and check rowCount()
// TODO: commit and return "order #N placed"
// TODO: catch the two failure kinds, rollBack(), return a reason
}Expected: PEN x2 is placed, LAMP x3 fails for lack of stock, DESK fails as an unknown sku, PEN x0 is refused and PEN x3 is placed. The final stock is LAMP 1 and PEN 0, with 2 orders stored.
Show hint
Read $pdo->lastInsertId() right after the INSERT. Put catch (PDOException) before catch (RuntimeException). In PHP 8 you may write catch (PDOException) with no variable when you do not need it.
Show solution
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE stock (
sku TEXT PRIMARY KEY,
qty INTEGER NOT NULL CHECK (qty >= 0)
)');
$pdo->exec('CREATE TABLE orders (
id INTEGER PRIMARY KEY,
sku TEXT NOT NULL,
qty INTEGER NOT NULL CHECK (qty > 0)
)');
$pdo->exec("INSERT INTO stock (sku, qty) VALUES ('PEN', 5), ('LAMP', 1)");
function placeOrder(PDO $pdo, string $sku, int $qty): string
{
if ($qty <= 0) {
return "$sku x$qty: rejected, quantity must be positive";
}
$pdo->beginTransaction();
try {
$insert = $pdo->prepare('INSERT INTO orders (sku, qty) VALUES (:sku, :qty)');
$insert->execute(['sku' => $sku, 'qty' => $qty]);
$orderId = $pdo->lastInsertId();
$update = $pdo->prepare('UPDATE stock SET qty = qty - :qty WHERE sku = :sku');
$update->execute(['qty' => $qty, 'sku' => $sku]);
if ($update->rowCount() !== 1) {
throw new RuntimeException('unknown sku');
}
$pdo->commit();
return "$sku x$qty: order #$orderId placed";
} catch (PDOException) {
$pdo->rollBack();
return "$sku x$qty: failed, not enough stock";
} catch (RuntimeException $e) {
$pdo->rollBack();
return "$sku x$qty: failed, " . $e->getMessage();
}
}
echo placeOrder($pdo, 'PEN', 2) . "\n";
echo placeOrder($pdo, 'LAMP', 3) . "\n";
echo placeOrder($pdo, 'DESK', 1) . "\n";
echo placeOrder($pdo, 'PEN', 0) . "\n";
echo placeOrder($pdo, 'PEN', 3) . "\n";
foreach ($pdo->query('SELECT sku, qty FROM stock ORDER BY sku') as $row) {
echo "stock {$row['sku']}: {$row['qty']}\n";
}
echo 'orders stored: ' . $pdo->query('SELECT COUNT(*) FROM orders')->fetchColumn() . "\n";Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Use PDO in exception mode and send values only through placeholders
- In autocommit every statement commits at once, so wrap dependent writes in a transaction
- commit() in the try, rollBack() in the catch, rethrow the exception, and check rowCount() too
- CHECK, UNIQUE and NOT NULL catch what slipped past PHP validation; know the MySQL differences
PDO Prepared Statements — PHP Documentation Group