使用事务处理的话,需要数据库引擎支持事务处理。比如 MySQL 的 MyISAM 不支持事务处理,需要使用 InnoDB 引擎。
使用 transaction 方法操作数据库事务,当发生异常会自动回滚,例如:
$trans_result = true;
$trans = M();
$trans->startTrans(); // 开启事务
try { // 异常处理
// 更新实施
$busbidList = M("busbid")->where($map)->select();
foreach($busbidList as $k => $v) {
$map['id'] = $busbidList[$k]['id'];
$result = M('busbid')->where($map)->data($data)->save();
if ($result === false) {
throw new Exception(“错误原因”);
}
}
} catch (Exception $ex) {
$trans_result = false;
// 记录日志
Log::record("== xxx更新失败 ==", 'DEBUG');
Log::record($ex->getMessage(), 'DEBUG');
}
if ($trans_result === false) {
$trans->rollback();
// 更新失败
$array['status'] = 0;
} else {
$trans->commit();
// 更新成功
$array['status'] = 1;
}
方式二:

M()->startTrans(); // 开启事务
if(操作失败) {
M()->rollback(); // 回滚
}else {
M()->commit(); // 提交
}

方式三:

1.引用TP5的think\Db类:
use think\Db;
2.下面为实现代码:
Db::startTrans();
//启动事务
try {
这里写SQL语句
Db::commit(); //提交事务
} catch (\PDOException $e) {
Db::rollback(); //回滚事务
}
