A transaction symbolizes a unit of work performed within a database management system (or similar system) against a database, and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in database. Transactions in a database environment have two main purposes:
- To provide reliable units of work that allow correct recovery from failures and keep a database consistent even in cases of system failure, when execution stops (completely or partially) and many operations upon a database remain uncompleted, with unclear status.
- To provide isolation between programs accessing a database concurrently. If this isolation is not provided, the program’s outcome are possibly erroneous. – Wikipedia
Any time you have a unit of work that is either sensitive to outside changes or needs the ability to rollback every change, if an error occurs, you have to use a transaction.
The strategy I use when working with transactions is the following:
TRY { DB->BEGIN_TRANSACTION RES = FIRST_QUERY IF(RES = ERR) THROW EXCEPTION RES = SECOND_QUERY IF(RES = ERR) THROW EXCEPTION DB->COMMIT } CATCH (EXCEPTION E) { DB->ROLLBACK }
Using php 5.4.x the DB->BEGIN_TRANSACTION is performed by
$mysqli_connection->autocommit(FALSE)
;
the DB->COMMIT is performed by
$mysqli_connection->autocommit(TRUE);
and the DB->ROLLBACK is performed by
$mysqli_connection->rollback();
$mysqli_connection->autocommit(TRUE);
The following function inserts the same value into two different table, if one of the two queries fails the databaase will be restored to initial state.
<?php public function myTransactionFunction($param) { // BEGIN TRANSACTION $mysqli_connection->autocommit(FALSE); try { // Insert new username in table1 $stmt1 = $mysqli_connection->prepare("INSERT INTO table1(username) VALUES(?)"); if(!$stmt1) throw new Exception("prepare query 1"); $result = $stmt1->bind_param("s", $param); if(!$result) throw new Exception("bind_param query 1"); $result = $stmt1->execute(); if(!$result) throw new Exception("execute query 1"); $stmt1->close(); // Insert new username in table2 $stmt2 = $mysqli_connection->>prepare("INSERT INTO table2(username) VALUES(?)"); if(!$stmt2) throw new Exception("prepare query 2"); $result = $stmt2->bind_param("s", $param); if(!$result) throw new Exception("bind_param query 2"); $result = $stmt2->execute(); if(!$result) throw new Exception("execute query 2"); $stmt2->close(); // COMMIT QUERIES $mysqli_connection->autocommit(TRUE); return(true); } catch( Exception $e ) { $mysqli_connection->rollback(); $mysqli_connection->autocommit(TRUE); echo("Error: ".$e->getMessage()); return(false); } } ?>
Gg1