Home >Backend Development >PHP Tutorial >php中对MYSQL操作之事务控制,回滚

php中对MYSQL操作之事务控制,回滚

WBOY
WBOYOriginal
2016-06-23 13:51:531202browse

<?php //事务控制,回滚//创建一个mysqli对象$mysqli = new MySQLi("主机名","mysql用户名","密码","数据库名");//判断是否链接成功if($mysqli->connect_error){	die($mysqli->connect_error);}//由于在事务提交中系统默认提交,故这里设置为FALSE先不提交$mysqli->autocommit(false);//其实这里系统已经相当在这里做个保存点,记录此时所有状态,回滚是回滚到这里//$mysqli->savepoint a;//写出对数据库的操作语句$sql1 = "insert into 表名 (字段名) values (对应字段的值)";$sql2 = "update 表名 set 字段名=值 where 条件";$sql3 = "delete from 表名 where 条件";//执行sql语句$res1 = $mysqli->query($sql1) or die ($mysqli->error);$res2 = $mysqli->query($sql2) or die ($mysqli->error);$res3 = $mysqli->query($sql3) or die ($mysqli->error);//判断是否都执行成功if(!$res1||!$res2||!$res3){	//只要有一条失败便回滚,都不执行,若设置滚回点,如a,加个参数a变滚回到a处	$mysqli->rollback();}else{	//一旦提交无法回滚,成功则提交	$mysqli->commit();}//关闭资源$musqli->close();?>

Statement:
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