如何从插入的行中获取最后一个id?

时间:2017-07-05 05:04:39

标签: php mysql

我正在尝试将主表的ID插入到我的事务表中。插入发生在循环内。

行为:

  • 插入主文件
  • 获取ID
  • 插入交易
  • Insert Master
  • 获取ID
  • 插入交易

控制器:

 //Insert Master
 foreach($arr_master as $res_master){

    /*$data['ID_REQUIREMENT_TRANS'] this is an auto-increment column. Inserted automatically*/

    $data['ID_REQUIREMENT']     = $res_master;
    $data['SENT_BY_DATE']       = date("Y-m-d H:i:s");                                                             
    $data['STATUS']             = 1;            

    $this->MAdmin->ins_assign_pic($data);

        //Insert Trans
        foreach($arr_trans as $res_trans){


            $data_d['ID_REQUIREMENT_TRANS'] = $id; //Need to get the last inserted id of the master table               
            $data_d['RECEIVED_BY']              = $res_trans; 
            $data_d['RECEIVED_BY_DATE']     = NULL; 
            $data_d['STATUS']                   = 1;            

            $this->MAdmin->ins_assign_pic_d($data_d);
        }
    }

型号:

function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    return $q_ins_assign_pic;

    $id = $this->db->insert_id(); 
    return $id;      //How to send this to my controller
    return true;
}

function ins_assign_pic_d($data_d){
    $q_ins_assign_pic_d = $this->db->insert('pm_requirement_assign_pic_d',$data_d);

    return $q_ins_assign_pic_d;
}

5 个答案:

答案 0 :(得分:0)

尝试控制器

$id = $this->MAdmin->ins_assign_pic($data);

和模型

function ins_assign_pic($data){
    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);
    //return $q_ins_assign_pic;

    $id = $this->db->insert_id(); 
    return $id;      //How to send this to my controller
   // return true;
}

答案 1 :(得分:0)

方式1

SELECT MAX( id ) FROM tableName;

方式2

SELECT tableName.id FROM tableName ORDER BY tableName.id DESC LIMIT 0,1;

答案 2 :(得分:0)

你在这里做错了。 一旦return调用函数,它就不会再执行。

<强>型号:

function ins_assign_pic($data){

    $q_ins_assign_pic   = $this->db->insert('pm_requirement_assign_pic',$data);

    if($q_ins_assign_pic){
        return $this->db->insert_id();
    } else {
        retun false;
    }

}

控制器:

 $newID = $this->MAdmin->ins_assign_pic($data);

答案 3 :(得分:0)

您可以从表中获取最大ID:

select max(id) from table

答案 4 :(得分:0)

mysqli_insert_id()是您正在寻找的功能。