Magento DB transaction commit rollback sniplet
Took me a while to find out how to do this… as there was no good examples on the web.
So, here it is… so I can find it again.
keywords:
db database transaction rollback commit magento zend.
try {
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$write->beginTransaction();
// do stuff here
$write->commit();
} catch (Exception $e) {
mage::log(__METHOD__ . ':' . __LINE__ . ': Rollback happened.');
$write->rollback();
}
Please drop a line if you found this useful. Thanks!
Categories: Uncategorized
Thanks
Wouldn’t this give errors whenever you want to rollback because $write would be null. $write should be set outside the try catch construct.
No, the instance of $write will exist inside the catch statement.
A quick test would show that rollback does in deed get triggered, when you throw an exception within the try statement.