Sometimes it is critical to ensure a group of queries are all executed successfully to maintain the integrity of our data. Let's say we have a banking app where we need to subtract funds from one account and add funds to another:


$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'");
$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'");

What if one of the queries fails? To mitigate the chances of misplacing our millions due to some possible error we must ensure that both queries are executed with the expected result before committing any changes to the data. This where transactions are useful. We can run the queries, then check if some conditions are met before committing the changes in the data:


$mysqli->begin_transaction();
$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'");
$a1=$mysqli->affected_rows();

$mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'");
$a2=$mysqli->affected_rows();

//Check 1 row affected by each query
if ($a1==1 && $a2==1) {
	
	//Everything looks OK, commit changes
	$mysqli->commit();
	
} else 

	//Something went wrong. Roll back to before begin_transaction()
	$mysqli->rollback();
}
$mysqli->close();

mysqli->begin_transaction() requires PHP 5.6 and above. For lower versions you can issue the MySQL commands directly like:

mysqli->query("START TRANSACTION")
mysqli->query("COMMIT")
mysqli->query("ROLLBACK")

Important note: Our tables must use an engine that supports transactions ie. InnoDB. Don't be silly like me and spend hours wondering why your transactions aren't working on MyISAM tables.

Add comment


Send