This seems rather obvious in retrospect, but this morning I encountered and issue trying to return the id value of the last record I inserted on a CMS where the record was inserted properly, but the id returned by the insert_id() helper function was always 0.
The original code was:
if($this->db->insert('posts',$data)) {
$this->db_session->set_flashdata('success','Post Added Successfully!');
redirect('/posts/edit/'.$this->db->insert_id());
}
Seemed simple enough: try to insert a record, on success set the flash message, and redirect to the record I inserted for further editing.
Well duh. The application uses the database for sessions, which meant that setting the flash message used a database insert (with no id to be returned). Once I clued into that the solution was simple, just store the id before setting the flash message:
if($this->db->insert('posts',$data)) {
$id = $this->db->insert_id();
$this->db_session->set_flashdata('success','Post Added Successfully!');
redirect('/posts/edit/'.$id);
}
Hardly mind blowing, but just an example of why you alway have to be conscience about what’s going on in the background of these helper functions when using a framework.

1 Comment to “CodeIgniter insert_id and db_session”
Nice tip