如何在codeigniter中插入查询后获取最后一个插入ID

如何在codeigniter中插入查询后获取最后一个插入ID

问题描述:

I'm having problem with my controller, I return the the last id I've inserted in the model

public function insert_cropsci($question_data) {    
    $this->db->insert('cropscience_bank', $question_data);
    $questionid =$this->db->insert_id();
    return $questionid;
}

but don't know how to get the id(id only) in my controller

My Controller:

switch ($subject) {
    case 1:
        $this->load->model('insertquestion_model');
        $this->insertquestion_model->insert_cropsci($question_data);
        //I don't know what to do here to get the id(id only)
    break;
}

need some help.

我的控制器出现问题,我返回我在模型中插入的最后一个ID p>

  public function insert_cropsci($ question_data){
 $ this-> db-> insert('cropscience_bank',$ question_data); 
 $ questionid = $ this-&gt  ; db-> insert_id(); 
返回$ questionid; 
} 
  code>  pre> 
 
 

但不知道如何获取id(仅限id) 我的控制器 p>

我的控制器: p>

 开关($ subject){
 case 1:
 $ this-> load-  > model('insertquestion_model'); 
 $ this-> insertquestion_model-> insert_cropsci($ question_data); 
 //我不知道该做什么来获取id(仅限id)
 break  ; 
} 
  code>  pre> 
 
 

需要一些帮助。 p> div>

You have to assign value in variable after assigning you will able to use it.

switch ($subject) {
            case 1:
                $this->load->model('insertquestion_model');
                $id = $this->insertquestion_model->insert_cropsci($question_data);
                echo $id;
                break;

Try this:

$this->db->insert('table', $data);
$insert_id = $this->db->insert_id();

You already have your value available, you just don't store it in a variable, from what I've seen looking at your code.

switch ($subject) {
    case 1:
        $this->load->model('insertquestion_model');
        $modelId = $this->insertquestion_model->insert_cropsci($question_data);
        // ^^^^^^^^^^^^^^^^^^^^^^^^^ return the $modelId from your controller!
        break;