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 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 easily; just drop the lines in bold into your model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86