This article mainly introduces php+mysqli transaction control to realize bank transfer, and the example analyzes the principle of transaction control and transaction rollback For usage tips, friends in need can refer to
The example in this article describes the method of implementing bank transfer through php+mysqli transaction control. Share it with everyone for your reference. The specific analysis is as follows:
Transaction control, which means that all statements will not be submitted until they are executed successfully. Otherwise, if a previous statement is executed successfully but the subsequent statement is not executed successfully, it will be rolled back to the state before execution. This application is illustrated through the case of bank transfer. When money is transferred out from one account, money must be transferred into the other account for it to be considered successful.
The code is as follows:
3 4 513 14
15
16
17
18
19
20
21
22
23
24
|
<🎜>//1. Create database connection object<🎜> <🎜>$mysqli = new MySQLi("localhost","root","123456","liuyan");<🎜> <🎜>if($mysqli->connect_error){ die($mysqli->connect_error); } $mysqli->query("set names 'GBK'"); $mysqli->autocommit(false); //First set autocommit to false, that is, no automatic submission $sql1 = "update account set balance=balance-2 where id=1;"; $sql2 = "update account set balance=balance+2 where id=2;"; $res1 =$mysqli->query($sql1) or die($mysqli->error); $res2 =$mysqli->query($sql2) or die($mysqli->error); if(!$res1 || !$res2){ echo "Transfer failed"; $mysqli->rollback();//If one of them fails, rollback }else{ $mysqli->commit();//Both statements are executed successfully, then submit echo "Transfer successful"; } ?> |