当前位置: 移动技术网 > IT编程>开发语言>PHP > ThinkPHP 3.2.2实现事务操作的方法

ThinkPHP 3.2.2实现事务操作的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了thinkphp 3.2.2实现事务操作的方法。分享给大家供大家参考,具体如下:

手册里说得非常清楚 :

5.3.19 事务支持

thinkphp提供了单数据库的事务支持,如果要在应用逻辑中使用事务,可以参考下面的方法:

启动事务:

$user->starttrans()

提交事务:

$user->commit()

事务回滚:

$user->rollback()

事务是针对数据库本身的,所以可以跨模型操作的 。

例如:

// 在user模型中启动事务
$user->starttrans()
// 进行相关的业务逻辑操作
$info = m("info"); // 实例化info对象
$info->save($user); // 保存用户信息
if (操作成功){
  // 提交事务
  $user->commit()
}else{
  // 事务回滚
  $user->rollback()
}

indexcontroller.class.php:

<?php
namespace sms\controller;
use think\controller;
class indexcontroller extends controller {
  public function index(){
    $data['operator'] = 'testss';
    m()->starttrans();
    $result = m('feehistory')->add($data);
    $result1 = $result2 = true;
    if(!empty($result)){
      $regdeldata['level'] = '111';
      $result1 = m('regdel')->add($regdeldata);
      $regdata['level'] = '101';
      $result2 = m('reg')->where("registrycode='13693536752-sjb-huax-12345678'")->save($regdata);
    }
    if(!empty($result) && !empty($result1) && !empty($result2) ){
      m()->commit();
      //$this->success('事物提交',__root__);
      echo '事物提交';
    }else{
      m()->rollback();
      //$this->error('事物回滚',__root__);
      echo '事物回滚';
    }
  }
}

更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。

希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网