/** * Database connection
* $conn = mysql_connect (' localhost ', ' root ', '); * mysql_select_db (' Test ', $conn); *mysql_query ("SET NAMES GBK"); * The table that supports transactions must be of type InnoDB * Only once in a transaction: *mysql_query (' Start TRANSACTION ');//Start Transaction *mysql_query (' ROLLBACK ');//ROLLBACK TRANSACTION *mysql_ Query (' commit ');//COMMIT TRANSACTION * Above is the most primitive wording
* Transaction Lock: If you update the same data synchronously or asynchronously, then we will use the transaction to lock the executing SQL statement until the transaction commits and the next data can execute * If there are multiple rollback transactions in a transaction, When a transaction is committed, all operations on the database are canceled before the first rollback until the start of the transaction, and all the database operations are still valid until the transaction is committed after the first rollback, so the rollback statement is generally placed only before the COMMIT TRANSACTION statement * If a transaction has no commit statement, All of the following database operations from the start of the transaction are executed (the execution method returns the right error), but there is no impact on the database, but the previous transaction is automatically committed when the next segment start statement is executed * The following example is a test file I wrote with an existing framework * HINT: Locked data query condition is already uniquely identified*/classTestextendscontroller{Private $db; function__construct ($options) {Parent:: __construct ($options, []); $this->db =New MYSQL(); } functionrun () {Try { $this->db->Begintran (); $state=$this->db->getfield ("Select State from test WHERE id = 1 for UPDATE"); if($state= = 2){ Throw New Exception(' Completed! ')); } $data=Array( ' State ' =>2 ); $res=$this->db->update (' Test ',$data, "Id=1"); if(!$res){ Throw New Exception(' Update succeeded! ')); } $this->db->Committran (); Dump (' Success '); die; } Catch(Exception $e ) { $this->db->Rollbacktran (); Dump ($e->getmessage ()); die; } }}
This example explains PHP's use of MySQL thing lock example, and has a note to explain in detail