Friday, February 5, 2010

Atomic transactions in Zend

If you have many database changes where all need to succeed or none at all do the following:

//Get a hold of the database adapter:
$model = new Model_DbTable_();
$adapter = $model->getAdapter();
$adapter->beginTransaction();
try {
//Do inserts, updates, deletes etc.
//Commit the changes and do rollback if it fails:
$adapter->commit();
}
catch (Exception $e) {
$user->getAdapter()->rollback();
//Print errors
$echo $e->getMessage();
}


or similarly:

$db->beginTransaction();
try {
$db->insert('server', array('key' => 'foo', 'value' => 'bar'));
$db->insert('server', array('key' => 'bar', 'value' => 'baz'));
$db->insert('server', array('key' => 'baz', 'value' => 'foo'));

$db->commit();
}
catch (Exception $e) {
$db->rollback();
$e->getMessage();
}


Solution found: http://devzone.zend.com/article/1367

No comments:

Post a Comment