素材牛VIP会员
为什么MySQL事务在PHP循环里不回滚?
 lh***81  分类:SQL代码  人气:1531  回帖:3  发布于6年前 收藏

引擎是innodb。
代码如下

        try{
            // …… ……一些代码
             
            $this->model->begin();
            if(!empty($goods_info) && !empty($shelf_num)){
                $order_arr['total_money'] = 0;
                $order_arr['good_num'] = 0;

                //根据传递商品编号及编号下的数量信息,循环插入订单详情表
                foreach ($goods_info as $val) {
                    $good_data = $this->model->findByid($val[0],array('price'));//查找商品价格信息
                    if(!empty($good_data) && $good_data[0]['price'] == $val[2]){
                    
                        $order_arr['total_money'] += $val[2]*$val[1];//订单总金额
                        $order_arr['good_num']    += $val[1];//订单商品总数
                        $order_detail['barcode']   = $val[0];//商品编号
                        $order_detail['good_num']  = $val[1];//商品数量
                        $order_detail['price']     = $val[2];//商品价格
                        $this->model->create();
                        $this->model->save($order_detail);//保存到订单详情表
                        
                    }else{
                        throw new Exception('001');
                    }
                    
                }

              // …… …… 一些代码
              
            $this->model->commit();
            $this->model->end();
            
        }catch(Exception $e) {
            $this->model->rollback();
            $arrData = $e->getMessage();
            echo $arrData;
        }
        
        
        
  
 标签:mysqlphp

讨论这个帖子(3)垃圾回帖将一律封号处理……

Lv6 码匠
ti***nx 学生 6年前#1

需要先开启事物。

Lv3 码奴
凤***奇 职业无 6年前#2
$good_data = $this->model->findByid($val[0],array('price'));//查找商品价格信息
if(!empty($good_data) && $good_data[0]['price'] == $val[2]){
    $this->model->create();
    $this->model->save($order_detail);//保存到订单详情表
    $this->model->commit();
}else{
    $res = $this->model->rollback();
    $this->model->end();
}

if判断的是商品信息,else里走回滚,那你回滚了啥呢,这逻辑不对。
试着用try catch:

$this->model->begin();
try{
    /* ...... */
    $this->model->save($order_detail);
    $this->model->commit();
}catch(Exception $e){
    $this->model->rollback();
} 
Lv3 码奴
Jo***91 CEO 6年前#3

数据库存储引擎使用的不对 要使用innodb

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取