Created
September 14, 2011 14:49
-
-
Save markrickert/1216768 to your computer and use it in GitHub Desktop.
Safely Handling Mysql Transactions in Zend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' => '[email protected]', | |
'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