Welcome to Joel Lipman .Com

Preparing Content...


Loading...

Our Website Development Notes

We hope this helps!

Articles // SQL // MySQL

MySQL Transactions in PHP

Wednesday, 14th December 2016
2,651 Reads

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:

  1.  
  2. $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'");  
  3. $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:

  1.  
  2. $mysqli->begin_transaction();  
  3. $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'-1000000 WHERE 'user' = 'Bob'");  
  4. $a1=$mysqli->affected_rows();  
  5.  
  6. $mysqli->query ("UPDATE 'accounts' SET 'balance' = 'balance'+1000000 WHERE 'user' = 'Fred'");  
  7. $a2=$mysqli->affected_rows();  
  8.  
  9. //Check 1 row affected by each query  
  10. if ($a1==1 && $a2==1) {  
  11.  
  12. //Everything looks OK, commit changes  
  13. $mysqli->commit();  
  14.  
  15. } else  
  16.  
  17. //Something went wrong. Roll back to before begin_transaction()  
  18. $mysqli->rollback();  
  19. }  
  20. $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.




Recent Comments

Gravatar for Art
Oracle: order by subquery missing right parenthesis
Hello, what if I would like to add rownum to that code, but in my case it's all is subquery? How can I do this ?

20 Jan


Gravatar for Robert
CharIndex Reverse - find occurrence starting from end of string in TSQL
Very helpful thanks! This worked for me as well, and is a little shorter. Not sure if there are drawbacks. SELECT RIGHT(@Haystack,CHARINDEX(@Delimiter,REVERSE(@Haystack))-LEN(@Delimiter))

29 Dec


Gravatar for Translation

27 Dec


Gravatar for Tibbe
JComments 2.3.0 with ReCaptcha in Joomla 2.5.x
Hi there, This looks like a great solution to get rid of spam comments. How to integrate this in Joomla 3.x? Step 2 I did in settings.xml, but no result in frontend. Kind Regards, Tibbe

16 Dec


Gravatar for sach|n
SSRS Repeat Headers in PDF Report
Yes its working for me..thnx Joel.

7 Oct