1.框架thinkphp 支持事务代码
public function testrollback(){
$model1 = D('item');
$model2 = D('vote');
$model1->startTrans();
$res1 = $model1->where('id = 5')->delete();
$res2 = $model2->where('id = 2')->delete();
dump($res1);
dump($res2);
if($res1 && $res2){
$model1->commit(); //只有$res1 和 $res2 都执行成功是才真正执行上面的数据库操作
dump("commit");
}else{
$model1->rollback(); // 条件不满足,回滚
dump("rollback");
}
dump("over");
exit;
}
只支持数据库和数据表都是 innoDB 的情况
public function rollbackoriginal1(){
$conn = mysql_connect('127.0.0.1','summerzi','summerzi') or die('DB connection failed!');
mysql_select_db('summer',$conn);
mysql_query('set names "GBK"');
mysql_query('BEGIN');
$sql1 = "INSERT INTO `summer_userdata`(`uid`,`type`,`target_id`) VALUES(41,1,233);";
$sql2 = "INSERT INTO `summer_userdata`(`uid`,`type`,`target_id`) VALUES(fdfd,2,235);";
$res1 = mysql_query($sql1);
$res2 = mysql_query($sql2);
dump($sql1);
dump($sql2);
dump($res1);
dump($res2);
if($res1 && $res2){
mysql_query('COMMIT');
dump('commit success!');
}else{
mysql_query('ROLLBACK');
dump('commit failed, rollback!');
}
mysql_query('END');
}
对于不支持事务的MyISAM引擎数据库可以使用表锁定的方法
public function rollbackoriginal2(){
$conn = mysql_connect('127.0.0.1','summerzi','summerzi') or die('DB connection failed!');
mysql_select_db('summer',$conn);
mysql_query('set names "GBK"');
mysql_query('SET AUTOCOMMIT=0');////设置mysql不自动提交,需自行用commit语句提交
$sql1 = "INSERT INTO `summer_userdata`(`uid`,`type`,`target_id`) VALUES(41,1,233);";
$sql2 = "INSERT INTO `summer_userdata`(`uid`,`type`,`target_id`) VALUES(44,2,235);";
//mysql_query("LOCK TABLES `hmbl_userdata` WRITE");//锁定表
$res1 = mysql_query($sql1);
$res2 = mysql_query($sql2);
dump($sql1);
dump($sql2);
dump($res1);
dump($res2);
//mysql_query("UNLOCK TABLES");//解除锁定
if($res1 && $res2){
mysql_query('COMMIT');
dump('commit success!');
}else{
mysql_query('ROLLBACK');
dump('commit failed, rollback!');
}
mysql_query("SET AUTOCOMMIT=1");
mysql_query('END');
}
原文地址:https://www.cnblogs.com/summerzi/archive/2015/04/05/4393790.html