Database transactions in Zend Framework
When a group of database changes must succeed or fail together, and how to write it in Zend Framework 1.
From the archive: first published on mohamedsharaf.net in April 2012. Rewritten and checked in 2026; some details may be out of date.
Most queries don’t need a transaction. You need one when several changes must happen all together or not at all: moving money between accounts, saving an order with its lines, updating stock with a sale.
In Zend Framework 1 (Zend_Db):
$db = Zend_Db_Table::getDefaultAdapter();
$db->beginTransaction();
try {
$db->insert('orders', $order);
$orderId = $db->lastInsertId();
foreach ($lines as $line) {
$db->insert('order_lines', $line + ['order_id' => $orderId]);
}
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
Two things to check: your tables must use a transactional engine (InnoDB, not the old MyISAM), and keep transactions short, because they hold locks while they run.
Today: Zend Framework is now the Laminas Project, and Zend Framework 1 reached end of life in 2016. The pattern (begin, try, commit, roll back on failure) is the same in every modern framework.