无法回滚原因MYSQL中只有【INNODB】和【BDB】类型的数据表才能支持事务处理!其他的类型是不支持的!
ALTER TABLE `这里改成您自己数据库表名` ENGINE='InnoDB';
//例如我表名是 admin
//执行下面语句 admin表就可以使用回滚功能了
ALTER TABLE `admin` ENGINE='InnoDB';
PHP Mysql回滚
<?php
/*方法一*/
/*************** transaction--1 ***************/
$conn = mysql_connect('localhost','root','root') or die ("数据连接错误!!!");
mysql_select_db('test',$conn);
mysql_query("set names 'GBK'"); //使用GBK中文编码;
//开始一个事务
mysql_query("BEGIN"); //或者mysql_query("START TRANSACTION");
$sql = "INSERT INTO `user` (`id`, `username`, `sex`) VALUES (NULL, 'test1', '0')";
$sql2 = "INSERT INTO `user` (`did`, `username`, `sex`) VALUES (NULL, 'test1', '0')";//这条我故意写错
$res = mysql_query($sql);
$res1 = mysql_query($sql2);
if($res && $res1){
mysql_query("COMMIT");
echo '提交成功。';
}else{
mysql_query("ROLLBACK");
echo '数据回滚。';
}
mysql_query("END");
/*方法二*/
/**************** transaction--2 *******************/
mysql_query("SET AUTOCOMMIT=0"); //设置mysql不自动提交,需自行用commit语句提交
$sql = "INSERT INTO `user` (`id`, `username`, `sex`) VALUES (NULL, 'test1', '0')";
$sql2 = "INSERT INTO `user` (`did`, `username`, `sex`) VALUES (NULL, 'test1', '0')";//这条我故意写错
$res = mysql_query($sql);
$res1 = mysql_query($sql2);
if($res and $res1){
mysql_query("COMMIT");
echo '提交成功。';
}else{
mysql_query("ROLLBACK");
echo '数据回滚。';
}
mysql_query("END"); //事务处理完时别忘记mysql_query("SET AUTOCOMMIT=1");自动提交
Mysqli回滚
<?php
// 假定数据库用户名:root,密码:123456,数据库:RUNOOB
$con=mysqli_connect("localhost","root","123456","RUNOOB");
if (mysqli_connect_errno($con))
{
echo "连接 MySQL 失败: " . mysqli_connect_error();
}
// 关闭自动提交
mysqli_autocommit($con,FALSE);
// 插入数据
$sql = mysqli_query($con,"INSERT INTO websites (name, url, alexa, country)
VALUES ('百度','https://www.baidu.com/','4','CN')");
$sql1 = mysqli_query($con,"INSERT INTO websites (name, url, alexa, country)
VALUES (Facebook','https://www.facebook.com/','2','USA')");//这条我故意写错
if($sql and $sql1){
// 提交事务
mysqli_commit($con);
echo '提交成功。';
}else{
//回滚事务
mysqli_rollback($con);
echo '数据回滚。';
}
// 关闭连接
mysqli_close($con);
?>