简体   繁体   中英

how to get last insert id after insert query in codeigniter

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.

Try this:

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

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

switch ($subject) {
case 1:
    $this->load->model('insertquestion_model');
    $id=$this->insertquestion_model->insert_cropsci($question_data);
    $id=$_SESSION['id'];
    // My be you can save as a session, use id in other form
break;

}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM