db-> insert_id()始终等于零

时间:2015-07-17 11:33:24

标签: php codeigniter

我的控制器中有一个AJAX函数:

public function add_display_row($shape, $rows) {
        $newRecord = array(
            'work_id' => '',
            'section_id' => (int)$rows + 1,
            'shape' => $shape
        );

        //insert new record after last
        $newro = array();
        for( $c=1; $c<6; $c++){
            $newRecord['ordinal'] = $c;
            $newRecord['size_id'] = $this->work_model->get_size_from_specs($shape, $c);
            $insNew = $this->work_model->save_new_featured_shape($newRecord);
            $newRecord['item_id'] = $insNew;
            array_push($newro, $newRecord);
        }

        print_r($newro);
    }

在模型中

public function save_new_featured_shape($record) {
      $this->db->trans_begin();
      $this->db->insert('work_featured', $record);

      if ($this->db->trans_status() === FALSE) {
        $this->db->trans_rollback();
        return false;
      } else {
        $this->db->trans_commit();
        $insert_id = $this->db->insert_id();
        return $insert_id;
      }
    }

在插入所有5条记录之后,我将数组返回给调用者,而item_id(应该是每个的插入ID)等于0。

我需要返回insert_id来构建我将插入DOM的DOM元素。

谁能明白为什么它是零?

1 个答案:

答案 0 :(得分:1)

修改add_display_row,如下所示。

   public function add_display_row($shape, $rows) {
    //$this->load->model('work_model');
    $newRecord = array(
        'work_id' => '',
        'section_id' => (int)$rows + 1,
        'shape' => $shape
    );
    $new_arr=array();
    //insert new record after last
    $newro = array();
    for( $c=1; $c<6; $c++){
        $newRecord['ordinal'] = $c;
        $newRecord['size_id'] =  $this->work_model->get_size_from_specs($shape, $c);
        $insNew = $this->save_new_featured_shape($newRecord);
        $new_arr['item_id'] = $insNew;
        $new_arr_arr=array_merge($newRecord,$new_arr);
        array_push($newro, $new_arr_arr);
    }
    echo "<pre>";
    print_r($newro);
    }

和模型功能如下。

  public function save_new_featured_shape($record) {
  $this->db->trans_begin();
  $this->db->insert('work_featured', $record);
    $insert_id = $this->db->insert_id();
  if ($this->db->trans_status() === FALSE) {
    $this->db->trans_rollback();
    return false;
  } else {
    $this->db->trans_commit();

    return $insert_id;
  }
}