Retrieve Last Insert ID with CodeIgniter's Active Record
When executing an insert query using CodeIgniter's Active Record, it's often necessary to retrieve the auto-incremented ID assigned to the newly inserted row. However, encountering issues with obtaining this ID can be frustrating.
Solution:
In your model's insert method, use the following steps:
<code class="php">function add_post($post_data) { $this->db->insert('posts', $post_data); $insert_id = $this->db->insert_id(); return $insert_id; }</code>
The insert_id() function retrieves the ID of the last inserted row.
If you're executing multiple inserts within a single transaction, you'll need to enclose the inserts within a transaction block:
<code class="php">$this->db->trans_start(); $this->db->insert('posts', $post_data); $insert_id = $this->db->insert_id(); $this->db->trans_complete();</code>
By following these steps, you can successfully retrieve the last insert ID after an insert operation using CodeIgniter's Active Record, ensuring accurate identification of the newly inserted record.
The above is the detailed content of How to Retrieve the Last Insert ID using CodeIgniter's Active Record?. For more information, please follow other related articles on the PHP Chinese website!