Finding the last insert id

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.

How to do it...

  1. 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; 
      } 
    } 

How it works...

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 ...

Get CodeIgniter 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.