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

Php 如何在多次插入后从表中获取最后一个id,php,codeigniter,activerecord,Php,Codeigniter,Activerecord,我将数据添加到三个表中,我需要获取第一个表的最后一个ID以在第二个表中使用,这在$this->db->insert_ID函数中是成功的,尝试使用第二个表仍然会给我第一个表的ID。我的代码安排如下: function addcrm() { //Post data collection array from the webform form $customerdata = array( "salutation"=>$this-

我将数据添加到三个表中,我需要获取第一个表的最后一个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);

    }

你在第二次通话中明显遗漏了什么

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

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

看到了吗

如果您使用的是自动增量表,您可以尝试使用MYSQL\u LAST\u INSERT\u ID;
尝试使用以下方法:

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

通过这种方式,您可以清楚地提出问题。

缺少解决问题的方法$leadID=$this->db->insert_id;->$leadID=$this->db->insert\u id;这很可能就是$this->db->insert\u id已经做过的事情。而且,它会突然将站点硬编码为仅mysql。我建议您尝试本机方法,因此如果它不起作用,您可能会忽略这个答案