PHP
Joomla! 6
Joomla! 5
Joomla! 3 (Legacy)
Database
Advanced
Run Atomic Operations with SQL Transactions (transactionStart and Rollback)
Wraps multi-table writes inside an InnoDB transaction with automatic rollback on failure to guarantee data integrity.
components/com_example/src/Model/OrderModel.php
<?php
declare(strict_types=1);
use Joomla\CMS\Factory;
use Joomla\Database\DatabaseInterface;
$db = Factory::getContainer()->get(DatabaseInterface::class);
try {
$db->transactionStart(true);
$db->insertObject('#__example_orders', $order, 'id');
$item->order_id = (int) $order->id;
$db->insertObject('#__example_order_items', $item);
$db->transactionCommit(true);
} catch (\Throwable $e) {
$db->transactionRollback(true);
throw $e;
}
Requires InnoDB tables (default across Joomla 4, 5 and 6).
components/com_example/src/Model/OrderModel.php
<?php
$db = JFactory::getDbo();
try {
$db->transactionStart();
$db->insertObject('#__example_orders', $order, 'id');
$db->transactionCommit();
} catch (Exception $e) {
$db->transactionRollback();
throw $e;
}
Legacy Joomla 3 transaction pattern via JFactory::getDbo().
Technical explanation and best practices
Whenever an operation writes to multiple related tables (such as an order and its line items), wrap the queries in transactionStart(true), transactionCommit(true) and transactionRollback(true).