Commit 9e785639 authored by Alexander Butenko's avatar Alexander Butenko

Added transaction helpers

parent 4f93e793
...@@ -943,4 +943,53 @@ class MysqliDb ...@@ -943,4 +943,53 @@ class MysqliDb
return clone $this; return clone $this;
} }
/**
* Begin a transaction
*
* @uses mysqli->autocommit(false)
* @uses register_shutdown_function(array($this, "_transaction_shutdown_check"))
*/
public function startTransaction () {
$this->_mysqli->autocommit (false);
$this->_transaction_in_progress = true;
register_shutdown_function (array ($this, "_transaction_status_check"));
}
/**
* Transaction commit
*
* @uses mysqli->commit();
* @uses mysqli->autocommit(true);
*/
public function commit () {
$this->_mysqli->commit ();
$this->_transaction_in_progress = false;
$this->_mysqli->autocommit (true);
}
/**
* Transaction rollback function
*
* @uses mysqli->rollback();
* @uses mysqli->autocommit(true);
*/
public function rollback () {
$this->_mysqli->rollback ();
$this->_transaction_in_progress = false;
$this->_mysqli->autocommit (true);
}
/**
* Shutdown handler to rollback uncommited operations in order to keep
* atomic operations sane.
*
* @uses mysqli->rollback();
*/
public function _transaction_status_check () {
if (!$this->_transaction_in_progress)
return;
echo "rolling all back";
$this->rollback ();
}
} // END class } // END class
...@@ -278,3 +278,18 @@ Please note that function returns SQL query only for debugging purposes as its e ...@@ -278,3 +278,18 @@ Please note that function returns SQL query only for debugging purposes as its e
$db->get('users'); $db->get('users');
echo "Last executed query was ". $db->getLastQuery(); echo "Last executed query was ". $db->getLastQuery();
``` ```
### Transaction helpers
Please keep in mind that transactions are working on innoDB tables.
Rollback transaction if insert fails:
```php
$db->startTransaction();
...
if (!$db->insert ('myTable', $insertData)) {
//Error while saving, cancel new record
$db->rollback();
} else {
//OK
$db->commit();
}
```
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment