如何在多次插入后从表中获取最后一个id

时间:2013-12-23 11:15:03

标签: php codeigniter activerecord

我正在向三个表中添加数据,我需要获取第二个表中使用的第一个表的最后一个ID,这对于$this->db->insert_id()函数是成功的,尝试使用第二个表仍然给了我第一个表的ID。我的代码的安排是:

    function addcrm() {

    //Post data collection array from the webform form
    $customerdata = array(

                    "salutation"=>$this->input->post('salutation'),  
                    "mobilenumber"=>$this->input->post('mobilenumber'), 
                    "emailaddress"=>$this->input->post('emailaddress') 

    );
    $this->db->insert('api_customer', $customerdata);

    $customer=$this->db->insert_id();
    $leaddata = array(
                    "fieldrep"=>$this->input->post('fieldrep'), 
                    "fk_customerID"=>$customer, 

                    "te"=>$this->input->post('takage'),
                    "othercost"=>$this->input->post('othercost')                    

    );

    $this->db->insert('api_lead', $leaddata);



  $leadID = $this->db->insert_id();

 for ($i =0; $i<count($_POST['w_product']); $i++){
     $productdata = array(
         "name" => $_POST['w_product'][$i],
         "type" => $_POST['w_type'][$i],
          "cost" => $_POST['w_cost'][$i],
         "fk_leadID"=> $leadID
          );
           $this->db->insert('api_prod',$productdata);

 }  
    $url = base_url('cXXXXXXXXXXXXXX);
    redirect($url);

    }

3 个答案:

答案 0 :(得分:0)

在第二次通话中你显然遗漏了一些东西。 ;)

$customer = $this->db->insert_id();

$leadIdD  = $this->db->insert_id;

请参阅? :)

答案 1 :(得分:0)

尝试使用以下方法:

$this->db->start_cache(); // Before query
$this->db->stop_cache(); // After query
$this->db->flush_cache(); // Clear query

通过这种方式,您可以进行清晰和刷新的查询。

答案 2 :(得分:-1)

如果您使用自动增量表,可以尝试使用MYSQL_LAST_INSERT_ID(); http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

相关问题