Skip to content

Instantly share code, notes, and snippets.

@markrickert
Created September 14, 2011 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrickert/1216768 to your computer and use it in GitHub Desktop.
Save markrickert/1216768 to your computer and use it in GitHub Desktop.
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