Home > Article > Backend Development > How to use Mysql transaction example code in php
MySQL transactions are mainly used to process data with large operations and high complexity. For example, in the personnel management system, if you delete a person, you need to delete the basic information of the person, and also delete the information related to the person, such as mailbox, articles, etc. In this way, these database operation statements constitute a transaction. ! This article mainly introduces the usage of Mysql transactions in PHP, which is a very important practical operation skill in PHP database programming. Friends who need it can refer to it
The specific examples are as follows:
<?php //数据库连接 $conn = mysql_connect('localhost', 'root', ''); mysql_select_db('test', $conn); mysql_query("SET NAMES GBK"); /* 支持事务的表必须是InnoDB类型 一段事务中只能出现一次: mysql_query('START TRANSACTION');//开始事务 mysql_query(' ROLLBACK ');//回滚事务 mysql_query('COMMIT');//提交事务 如果一段事务中出现多次回滚事务,则在,提交事务时只将第一次回滚前至开始事务后对数据库的所有操作取消,第一次回滚后至提交事务前所有对数据库操作仍将有效,所以一般将回滚语句仅放在提交事务语句前 如果一段事务无提交语句,则从开始事务时以下的所有对数据库操作虽执行(执行方法返回对错),但对数据库无影响,但是在执行下段开始事务语句时,前段事务自动提交 */ mysql_query('START TRANSACTION'); $isBad = 0; $ins_testTable1 = "INSERT INTO testtable1(NAME,age)VALUES('first',23)"; if(!mysql_query($ins_testTable1)){ $isBad =1; } //插入语句字段名有错 $ins_testTable2 = "INSERT INTO testtable1(NAME,ages)VALUES('second','24')"; if(!mysql_query($ins_testTable2)){ $isBad =1; } if($isBad == 1){ echo $isBad; mysql_query('ROLLBACK '); } mysql_query('COMMIT'); mysql_close($conn); ?>
The above is the detailed content of How to use Mysql transaction example code in php. For more information, please follow other related articles on the PHP Chinese website!