Codeigniter Try Catch Transaction

时间:2015-11-09 15:07:49

标签: php mysql codeigniter transactions

我有这个事务并尝试使用catch语句来检查每个$_POST['count']的值是否不小于0. *仅当if语句为false时才会发生回滚,它不会包含过去的更新是不正确的

$this->db->trans_begin();
foreach($_POST['ID'] as $val => $r)
{

        //Gets Count            
        $this->db->select('count');
        $this->db->from('table1');
        $this->db->where('table_id', $r);
        $oc = $this->db->get()->row('count');
        $nc = (($oc) - $_POST['count'][$val]);

        //Gets Total
        $this->db->select('cost');
        $this->db->from('table1');
        $this->db->where('table_id', $r);
        $ot = $this->db->get()->row('cost');
        $total = ($ot + $total);
        try{
            if($nc > 0){
                //Updates Quantity  
                $process = array(
                    'current_count' => $nc,
                );

                $this->db->where('product_id', $rm);
                $this->db->update('products', $process);
            }
        }
        catch(Exception $e){
            $this->db->trans_rollback();
            $this->session->set_flashdata('error','Production Failed. 1 or more Raw Materials required for production is insufficient.');
            exit;
        }
}
$this->db->trans_commit();

之后有插入和更新语句,但我想要的是,如果发现异常显然exit;语句没有这样做,则停止整个过程

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。也许最简单的就是这个。

<强>型号:

//I'm making the function up cause you don't show it
public function do_something(){ 

//all code the same up to here...

if($nc > 0){
    //Updates Count
    $process = array('count' => $nc);

    $this->db->where('table_id', $r);
    $this->db->update('table1', $process);
 } else {
     $this->db->trans_rollback();
     throw new Exception('Model whats_its_name has nothing to process');
 }

模型中的catch语句将捕获数据库类可能抛出的任何异常。 (他们是否会抛出任何例外情况?我不知道。)

<强>控制器

try{
    $this->some_model->do_something();
}
catch (Exception $e) {
 //catch the exception thrown in do_something()
 //additional handling here
}

所有这一切,在致电$_POST['count']

之前,最好先检查$this->some_model->do_something();是否有合适的值