<?php $mysqli = new mysqli("127.0.0.1","root","111111","test"); if ($mysqli->connect_errno){ echo "Failed to connect to MySQL: " . $mysqli->connect_error; } //默认auto-commit 是打开的,可直接提交sql语句 $b1 = $mysqli->query("INSERT INTO test (id,name) values (0,'000')"); //若要执行事务,先关闭auto-commit //关闭 auto-commit $mysqli->autocommit(false); $res1 = $mysqli->query("INSERT INTO test (id,n1ame) values (1,'111')"); $b2 = $mysqli->query("INSERT INTO test (id,name) values (2,'222')"); //有一条失败则回滚,全部成功则提交 if(!$res1 || !$b2){ echo '回滚!'; $mysqli->rollback(); } else { echo '提交!'; $mysqli->commit(); } //若想再次自动提交非事务语句,要打开auto-commit $mysqli->autocommit(true); $b3 = $mysqli->query("INSERT INTO test (id,name) values (3,'333')"); //关闭连接 $mysqli->close(); ?>