Search code examples
codeignitercodeigniter-3

CodeIgniter's insert_id() function is always returning 1


I have the following:

function insert_data($table=0,$data)
    {
        if($table !== 0)
        {
            if ($this->db->table_exists($table))
            {
                $this->db->insert($table,$data);
                return $this->db->insert_id();
            }
        }
        return 0;
    } 

I call it using

...
$insert_info = array(
    'event_id'      =>$id,
    'checklist_name'=>$_POST['event_name'].' Checklist',
    'checklist_type'=>2,
    'status'        =>1,
    'created_by'    =>$this->session->userdata('superadmin_id'),
    'created_date'  =>date('Y-m-d H:i:s'),
    'updated_by'    =>$this->session->userdata('superadmin_id'),
    'updated_date'  =>date('Y-m-d H:i:s')
    );
$new_checklist_id = $this->db->insert('checklist_event',$insert_info);
echo $new_checklist_id;
die();
...

However, 1 is always echo'd. I can confirm there are a dozen or so records in the table so unsure why it's returning 1 each time. Any suggestions?

This is the structure of the table

enter image description here


Solution

  • However, 1 is always echo'd

    you actually echo'ing out the return of the Query Builder Class insert() function, which is either true or false.

    use this approach:

    $this->db->insert('checklist_event',$insert_info);
    $new_checklist_id = $this->db->insert_id();
    echo $new_checklist_id; die();
    

    You seem not to be calling the function insert_data($table=0,$data) at all