PHP PDO Transactions and Auto-Commit
Now that you are connected via PDO, before starting queries, you must first understand how PDO manages transactions.
Transactions support four major characteristics (ACID):
- Atomicity
- Consistency
- Isolation
- Durability
In plain terms, any operation performed within a transaction, even if executed in stages, is guaranteed to be safely applied to the database and, when committed, will not be disturbed by other connections.
Transaction operations can also be automatically rolled back on request (assuming they have not been committed yet), which makes error handling in scripts easier.
Transactions are usually implemented by "accumulating" a batch of changes and then making them take effect simultaneously; the benefit of doing so is that it can greatly improve the efficiency of these changes.
In other words, transactions can make scripts faster and potentially more robust (though you need to use transactions correctly to gain such benefits).
Unfortunately, not every database supports transactions, so when a connection is first opened, PDO needs to run in the so-called "auto-commit" mode.
Auto-commit mode means that, if the database supports it, every query run has its own implicit transaction; if the database does not support transactions, then there is none.
If a transaction is needed, it must be started with the PDO::beginTransaction() method. If the underlying driver does not support transactions, a PDOException is thrown (regardless of the error handling setting, this is a serious error condition).
Once a transaction has started, it can be completed with PDO::commit() or PDO::rollBack(), depending on whether the code in the transaction ran successfully.
Note: PDO only checks at the driver level whether transaction capability exists. If some runtime conditions mean transactions are unavailable, and the database service accepts the request to start a transaction, PDO::beginTransaction() will still return TRUE without error. Trying to use transactions in a MyISAM table in a MySQL database is a good example.
When the script ends or the connection is about to be closed, if there is still an unfinished transaction, PDO will automatically roll it back. This safety measure helps avoid an inconsistent state when the script terminates unexpectedly—if the transaction was not explicitly committed, it is assumed that something went wrong, so a rollback is performed to ensure data safety.
Note: Automatic rollback can only occur after a transaction has been started via PDO::beginTransaction(). If a transaction is started by manually issuing a query, PDO cannot know about it and thus cannot roll back when necessary.
Executing Batch Processing in a Transaction:
In the example below, suppose we create a set of entries for a new employee, assigning an ID of 23. In addition to registering this person's basic data, we also need to record their salary.
The two updates are simple to do separately, but by enclosing them in PDO::beginTransaction() and PDO::commit() calls, you can ensure that no one else can see these changes until they are completed.
If an error occurs, the catch block rolls back all changes made since the transaction started and outputs an error message.
true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
values (23, 50000, NOW())");
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>
It is not limited to changes within a transaction; you can also issue complex queries to extract data, and use that information to build more changes and queries; while the transaction is active, you can ensure others cannot make changes while the operation is in progress.
PHP PDO Reference Manual