Example of php + mysql transaction processing detailed analysis instance, mysql Transaction Processing
1. The data engine innodb uses begin, rollback, and commit to commit transactions. If an error occurs after the begin starts the transaction, the rollback transaction is rolled back or there is no error. Then, the commit submits the transaction for confirmation.
Start transaction start is the statement block executed between the begin and end of the transaction. set autocommit = 0 does not allow the transaction to be automatically committed after setting set autocommit = 1.
The following is an example of a data table engine that supports transaction processing.
Mysql_query ("start transaction"); mysql_query ("set autocommit = 0"); mysql_query ("begin"); $ SQL = "insert into student (name, num) values ('test1', '0') "; $ sql2 =" insert into student (name, num) values (null, '0 ')"; // error $ res = mysql_query ($ SQL); $ res1 = mysql_query ($ sql2); if ($ res & $ res1) {mysql_query ("commit "); echo 'submission successful. <Br/> ';} else {mysql_query ("rollback"); echo' data rollback. <Br/> ';} mysql_query ("set autocommit = 1"); mysql_query ("end ");
2. You can use the table locking method for MyISAM engine databases that do not support transactions:
MyISAM & InnoDB support, and lock tables can LOCK the table used for the current thread. If the table is locked by other threads, blocking occurs until all the locks can be obtained. Unlock tables can release any lock maintained by the current thread. When the thread publishes another lock tables, or when the connection to the server is closed, all TABLES locked by the current thread are implicitly unlocked.
The following example shows how to use table locks for transactions that do not support commit.
Mysql_query ("lock tables student write"); // lock the write of the student table. It can also be read $ SQL = "insert into student (name, num) values ('sansheng h3 ', '0') "; $ res = mysql_query ($ SQL); if ($ res) {echo 'submitted successfully .! <Br/> ';} else {echo' failed! <Br/> ';} mysql_query ("unlock tables"); // UNLOCK
Example of the complete code above: http://pan.baidu.com/s/1pLkbkKj
Password: bh49