Using CodeIgniter to get the Last Inserted ID
Sunday, June 14th, 2009I often need to know the id of the last inserted record into a table. In the past, I’ve used a PHP function:
function getLastInserted($table, $id) { $query = "SELECT $id as maxID from $table where $id = LAST_INSERT_ID()"; $result = $this->runQuery($query); $row = mysql_fetch_row($result); return $row[0]; } |
To duplicate this using CodeIgniter’s Active Record, I could write:
function getLastInserted($table, $id) { $this->db->select_max($id); $Q = $this->db->get($table); $row = $Q->row_array(); return $row[$id]; } |
But, I learned that there is an even faster way that uses one of CodeIgniter’s Helper functions. Immediately after a record has been inserted into the database, I simply call:
$id = $this->db->insert_id(); |
Although, I am not sure how CodeIgniter knows which field is the primary key, it seems to work.



June 27th, 2009 at 5:11 pm
It works because MySQL has built-in support for this. In the PHP MySQL module, there is a function called mysql_insert_id() that will return the last inserted primary key for the last insert.
CodeIgniter is simply wrapping around this functionality.
January 11th, 2011 at 12:33 pm
thanks for the post, $id = $this->db->insert_id(); is really easy and nice.
January 28th, 2011 at 12:24 pm
Thanks guys.. specially Joe for enlightening about called mysql_insert_id()
March 31st, 2011 at 10:17 am
Thanks for this dude, really helpful