Skip to content

Commit 9e78563

Browse files
committed
Added transaction helpers
1 parent 4f93e79 commit 9e78563

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

MysqliDb.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,4 +943,53 @@ public function copy ()
943943
return clone $this;
944944
}
945945

946+
/**
947+
* Begin a transaction
948+
*
949+
* @uses mysqli->autocommit(false)
950+
* @uses register_shutdown_function(array($this, "_transaction_shutdown_check"))
951+
*/
952+
public function startTransaction () {
953+
$this->_mysqli->autocommit (false);
954+
$this->_transaction_in_progress = true;
955+
register_shutdown_function (array ($this, "_transaction_status_check"));
956+
}
957+
958+
/**
959+
* Transaction commit
960+
*
961+
* @uses mysqli->commit();
962+
* @uses mysqli->autocommit(true);
963+
*/
964+
public function commit () {
965+
$this->_mysqli->commit ();
966+
$this->_transaction_in_progress = false;
967+
$this->_mysqli->autocommit (true);
968+
}
969+
970+
/**
971+
* Transaction rollback function
972+
*
973+
* @uses mysqli->rollback();
974+
* @uses mysqli->autocommit(true);
975+
*/
976+
public function rollback () {
977+
$this->_mysqli->rollback ();
978+
$this->_transaction_in_progress = false;
979+
$this->_mysqli->autocommit (true);
980+
}
981+
982+
/**
983+
* Shutdown handler to rollback uncommited operations in order to keep
984+
* atomic operations sane.
985+
*
986+
* @uses mysqli->rollback();
987+
*/
988+
public function _transaction_status_check () {
989+
if (!$this->_transaction_in_progress)
990+
return;
991+
992+
echo "rolling all back";
993+
$this->rollback ();
994+
}
946995
} // END class

readme.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,3 +278,18 @@ Please note that function returns SQL query only for debugging purposes as its e
278278
$db->get('users');
279279
echo "Last executed query was ". $db->getLastQuery();
280280
```
281+
282+
### Transaction helpers
283+
Please keep in mind that transactions are working on innoDB tables.
284+
Rollback transaction if insert fails:
285+
```php
286+
$db->startTransaction();
287+
...
288+
if (!$db->insert ('myTable', $insertData)) {
289+
//Error while saving, cancel new record
290+
$db->rollback();
291+
} else {
292+
//OK
293+
$db->commit();
294+
}
295+
```

0 commit comments

Comments
 (0)