← PHP for real applications
05 / 8 · 23 MIN

PDO transactions and partial failures

Group related changes and check transaction boundaries.

Understand the concept

A transaction treats related database changes as a unit under the engine’s guarantees. With PDO, beginning, committing, and rolling back are explicit decisions. An exception alone does not guarantee application code called rollback. DDL and drivers can have specific behavior requiring confirmation.

Apply and decide

Avoid unnecessary slow calls inside transactions holding resources. Sending an email is not undone by SQL rollback. When a result must trigger external work, an outbox record in the same transaction can support controlled later processing. Check concurrency and duplication; beginTransaction does not automatically solve them.

Guided workplace application

In a fictional service, confirming an order also requires storing an audit event. If both belong to the same transactional database, one transaction can commit or roll back the two DML writes. Control error handling and do not assume every exception executes the rollback your code expects. DDL has its own rules: in MySQL, statements such as CREATE TABLE can cause implicit commit. A sent email remains outside SQL rollback scope. An outbox stores the change and sending intent in one transaction; a worker sends later. If the worker fails between delivery and marking, it may repeat. Retain event identity, define idempotent consumption, and monitor pending work. A transaction should not remain open while waiting for slow external calls without assessing held locks and resources.

IN PRACTICE

Updating the order and writing its outbox event in one transaction avoids committing only half that intention in the database.

Common pitfalls

Mixing DDL without checking implicit commit; assuming external-effect rollback; promising unique delivery from outbox alone.

Related topics: HTTP, sessions, and per-resource authorization · Explicit types and comparisons

Take this idea with you

A transaction has a scope; external effects need their own strategy.

Create account

Reference: PHP manual: Transactions and auto-commit · PHP 8.5 reference; DR PHP 2026.2; new fixtures executed on PHP 8.3.17