参考文档 http://liuxufei.com/weblog/jishu/971.html
<?php
$tranDb = new Model();
// 启动事务
$tranDb->startTrans();
// 准备数据
$sql = array('aaa' => 1);
$res1 = $tranDb->table(C('DB_PREFIX').'user_count')->where('uid = 1')->save($sql);
$res2 = $tranDb->table(C('DB_PREFIX').'hotel_order')->where('orderid = 1000')->save(array('status' => 1));
if ($res1 && $res2) {
// 提交事务
$tranDb->commit();
echo '<div style="color:blue;">成功</div>';
}
else {
// 事务回滚
$tranDb->rollback();
echo '<div style="color:red;">失败</div>';
}
2、MySQL 原生事务回滚
<?php
$conn = mysql_connect('127.0.0.1', 'root', 'root');
mysql_select_db('shop_test');
mysql_query('SET NAMES UTF8');
# 开启事务
mysql_query("START TRANSACTION");
$sql1 = "INSERT INTO `user_order` VALUES ('1', 'luchanghong', '10', '2')";
$sql2 = "UPDATE `user_account` SET `money` = `money` - 10*2 WHERE `user` = 'luchanghong'";
$res1 = mysql_query($sql1);
$res2 = mysql_query($sql2);
// if (mysql_errno()){
if ($res1 && $res2){
// 提交事务
mysql_query('COMMIT');
echo "成功";
}else{
// 事务回滚
mysql_query('ROLLBACK');
echo "失败";
}
3、PDO 事务回滚
<?php
try {
$dsn = 'mysql:dbname=sunyang;host=localhost';
$user_name = 'root';
$user_psw = 'root';
$pdo = new PDO($dsn, $user_name, $user_psw);
//开始事务
$pdo->beginTransaction();
$pdo->exec('update employee set emp_age=28 where emp_id=3');
$pdo->exec('delete from employee where emp_id=2');
//提交事务
$pdo->commit();
} catch (Exception $e) {
//回滚事务
$pdo->rollBack();
echo $e->getMessage();
}