Returning the Primary Key of the last inserted row can be useful in instances where you may wish to write data to more than one table and whose data may be related via the keys. CodeIgniter provides support for returning the last inserted key.
Add or adapt the following code into a model:
function insert($data) { if ($this->db->insert($data, 'table_name')) { return $this->db->last_id(); } else { return false; } }
Take a look at the lines in bold. We test for the returned value of $this->db->insert($data);
, which will return true if successful and false if there was an error. If the returned value is true, we grab the Primary Key of the last inserted record for this connection; this value along with return $this->db->insert_id();
is returned from the model to the code that called the function. If the database insert was unsuccessful, it would return false. You can adapt the above recipe...