CodeIgniter last inserted ID

Created September 26, 2010

At times when you insert a new row into a database you may need to capture that last unique ID that has just been added to the database. Well, lucky for you.... getting the last database inserted ID using CodeIgniter is very simple. All you need to do is call the $this->db->insert_id(); function after you have just finished inserting a new row into the database and this will return that last 'unique' ID. Example:

$data = array(
               'title' => 'My title' ,
               'name' => 'My Name' ,
               'date' => 'My date'

$this->db->insert('mytable', $data); 

$last_id = $this->db->insert_id();

Now, $last_id variable will contain the last variable of the row that has just been inserted into any table.