How to Use Transactions in PHP: Simple Guide with Examples
In PHP, use
PDO to manage transactions by calling beginTransaction() to start, commit() to save changes, and rollBack() to undo changes if errors occur. This ensures your database operations are safe and consistent.Syntax
Transactions in PHP using PDO follow this pattern:
beginTransaction(): Starts the transaction.commit(): Saves all changes made during the transaction.rollBack(): Reverts changes if something goes wrong.
This helps keep your data safe by grouping multiple operations as one unit.
php
<?php $pdo->beginTransaction(); // perform queries $pdo->commit(); // or if error $pdo->rollBack(); ?>
Example
This example shows how to use transactions to insert two related records safely. If the second insert fails, the first one is undone.
php
<?php try { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->beginTransaction(); $pdo->exec("INSERT INTO accounts (name, balance) VALUES ('Alice', 1000)"); $pdo->exec("INSERT INTO accounts (name, balance) VALUES ('Bob', 500)"); $pdo->commit(); echo "Transaction completed successfully."; } catch (Exception $e) { $pdo->rollBack(); echo "Transaction failed: " . $e->getMessage(); } ?>
Output
Transaction completed successfully.
Common Pitfalls
Common mistakes when using transactions include:
- Not setting
PDO::ERRMODE_EXCEPTION, so errors don’t trigger rollback. - Forgetting to call
commit(), leaving the transaction open. - Not handling exceptions properly, causing inconsistent data.
Always use try-catch blocks and set error mode to exceptions.
php
<?php // Wrong way: no error mode and no try-catch $pdo->beginTransaction(); $pdo->exec("INSERT INTO accounts (name) VALUES ('Charlie')"); // If error here, no rollback $pdo->exec("INVALID SQL"); $pdo->commit(); // Right way: try { $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->beginTransaction(); $pdo->exec("INSERT INTO accounts (name) VALUES ('Charlie')"); $pdo->exec("INVALID SQL"); $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); echo "Failed: " . $e->getMessage(); } ?>
Quick Reference
| Method | Description |
|---|---|
| beginTransaction() | Starts a new transaction |
| commit() | Saves all changes made in the transaction |
| rollBack() | Reverts all changes if an error occurs |
| setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) | Enables exceptions for errors |
Key Takeaways
Always start a transaction with beginTransaction() before your queries.
Use commit() to save changes or rollBack() to undo if errors happen.
Set PDO error mode to exceptions to catch problems easily.
Wrap transactions in try-catch blocks to handle errors safely.
Transactions keep your database consistent by grouping operations.