Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Safely Handling Mysql Transactions in Zend
<?php
// the below code assumes you have the private/protected
// variable $this->_db set to your database adapter.
// begin the transaction
$this->_db->beginTransaction();
try {
// mock insert into a user table
$result = $this->_db->insert('users', array(
'name' => 'Corey',
'email' => 'duplicate@alreadyexists.com',
'password' => sha1('FakeSalt' . 'FakePass'),
'created_ts' => time(),
'modified_ts' => NULL
));
// begin process of roles insertion
if ($result) {
// grab the user id from the last insert
$user_id = $this->_db->lastInsertId();
// insert into a mock user roles table
$result = $this->_db->insert('users_roles', array(
'user_id' => $user_id,
'role_id' => 1
));
// on success, commit transaction and return the user_id
if ($result) {
$this->_db->commit();
return $user_id;
}
}
} catch (Exception $e) {
// THIS IS WHERE THE MAGIC HAPPENS
// rollback
$this->_db->rollback();
// throw the same exception so it bubbles
// back up to the error controller
throw $e;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.