Search code examples
phpcodeignitermysqlicodeigniter-3last-insert-id

At insert_id() , get last insert id in codeigniter extra 1 is coming with id


When using insert_id() to receiving the last Auto increment insert ID , then extra 1 is coming with every id , when doing echo print($insert_id) at MODEL in CodeIgniter.

For Example: My last Auto Increment id at database column is 50 when doing echo ($insert_id); it showing me 501 as my last increment id. Very strange. I could not able to find out the problem why extra 1 is coming. Any suggestion, please help me out.

My Another question is after receiving the Last Insert Id, how to receive the ID to Controller file at Codeigniter from Modal File.

Modal

public function create($data = [])
{	 
   $this->db->insert($this->table,$data);
   $insert_id = $this->db->insert_id();
   echo print_r($insert_id);exit;
		  
   //return $insert_id ;
}


Solution

  • Hope this will help you :

    Note : Use only echo to print the insert id in your model; and to get the id in controller just return $insert_id

    Your model should be like this :

    public function create($data = [])
    {   
       if (! empty($data))
       { 
         $this->db->insert($this->table,$data);
         $insert_id = $this->db->insert_id();
         return $insert_id;
       }
    }
    

    In your controller :

    Note : make sure you have loaded your model either in autoload or in controller

    public function method_name()
    {
      $data = ['your insert data in array'];
      $id = $this->model_name->create($data);
      echo $id;//you will get the id;
    }