鍍金池/ 問答/PHP  數(shù)據(jù)庫/ 為什么MySQL事務在PHP循環(huán)里不回滾?

為什么MySQL事務在PHP循環(huán)里不回滾?

引擎是innodb。
代碼如下

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

                //根據(jù)傳遞商品編號及編號下的數(shù)量信息,循環(huán)插入訂單詳情表
                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];//訂單商品總數(shù)
                        $order_detail['barcode']   = $val[0];//商品編號
                        $order_detail['good_num']  = $val[1];//商品數(shù)量
                        $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;
        }
        
        
        
  
回答
編輯回答
近義詞

數(shù)據(jù)庫存儲引擎使用的不對 要使用innodb

2017年10月4日 06:49
編輯回答
毀與悔
$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();
} 
2018年8月8日 19:15