How to use Mysql transaction example code in php

怪我咯
Release: 2023-03-14 12:12:02
Original
2558 people have browsed it

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(&#39;localhost&#39;, &#39;root&#39;, &#39;&#39;);
mysql_select_db(&#39;test&#39;, $conn);
mysql_query("SET NAMES GBK");

/*
支持事务的表必须是InnoDB类型
一段事务中只能出现一次:
mysql_query(&#39;START TRANSACTION&#39;);//开始事务
mysql_query(&#39; ROLLBACK &#39;);//回滚事务
mysql_query(&#39;COMMIT&#39;);//提交事务

如果一段事务中出现多次回滚事务,则在,提交事务时只将第一次回滚前至开始事务后对数据库的所有操作取消,第一次回滚后至提交事务前所有对数据库操作仍将有效,所以一般将回滚语句仅放在提交事务语句前
如果一段事务无提交语句,则从开始事务时以下的所有对数据库操作虽执行(执行方法返回对错),但对数据库无影响,但是在执行下段开始事务语句时,前段事务自动提交
*/
mysql_query(&#39;START TRANSACTION&#39;);
$isBad = 0;

$ins_testTable1 = "INSERT INTO testtable1(NAME,age)VALUES(&#39;first&#39;,23)";
if(!mysql_query($ins_testTable1)){
  $isBad =1;
}
//插入语句字段名有错
$ins_testTable2 = "INSERT INTO testtable1(NAME,ages)VALUES(&#39;second&#39;,&#39;24&#39;)";
if(!mysql_query($ins_testTable2)){
  $isBad =1;
}
if($isBad == 1){
  echo $isBad;
  mysql_query(&#39;ROLLBACK &#39;);
}
mysql_query(&#39;COMMIT&#39;);
mysql_close($conn);
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!