【问题标题】:Codeigniter Try Catch TransactionCodeigniter 尝试捕获事务
【发布时间】:2016-02-10 06:33:51
【问题描述】:

我有这个事务并尝试使用 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; 语句没有这样做

【问题讨论】:

  • 你使用的是INNODB数据库还是MYISAM数据库
  • 您最感兴趣的是测试 $nc >0 并在不是时停止进程?
  • 上面显示的代码是在模型还是控制器中?
  • @DFriend 是的,如果捕获到异常并且上面显示的代码是模型,我还需要停止进程
  • 该代码中实际上没有抛出异常(CodeIgniter 也不这样做)。

标签: php mysql codeigniter transactions


【解决方案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
}

话虽如此,在致电$this->some_model->do_something(); 之前检查$_POST['count'] 的适当值可能是明智之举

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2019-08-25
    • 2011-03-09
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多