$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(); //回滾事務 }
