使用事务之前,先确保数据库的存储引擎支持事务操作。
- MyISAM:不支持事务,主要用于读数据提高性能
- InnoDB:支持事务、行级锁和并发
- Berkeley DB:支持事务
<?php/** * 事务测试 */public function transaction(){$modelA = model(‘A‘);$modelA->startTrans(); // 开启事务A$result = $modelA->save($data1);if($result === false){$modelA->rollBack(); // 事务A回滚$this->error(‘添加A信息失败,请重试‘);} $modelB = model(‘B‘);$modelB->startTrans(); // 开启事务B$result = $modelB->save($data2);if($result === false){$modelB->rollBack(); // 事务B回滚$modelA->rollBack(); // 事务A回滚$this->error(‘添加B信息失败,请重试‘);} $modelC = model(‘C‘);$modelC->startTrans(); // 开启事务C$result = $modelC->save($data3);if($result === false){$modelC->rollBack(); // 事务C回滚$modelB->rollBack(); // 事务B回滚$modelA->rollBack(); // 事务A回滚$this->error(‘添加C信息失败,请重试‘);} // 提交事务$modelC->commit();$modelB->commit();$modelA->commit(); $this->success(‘注册成功‘, url(‘admin/index/index‘));}
参考链接:tp3模型的事务支持:TP模型---事务支持
ThinkPHP 模型 - 事务支持
原文地址:http://www.cnblogs.com/mingc/p/7496901.html