How to Retrieve the Auto-Incremented ID after an Insert Query in CodeIgniter Active Record
When using CodeIgniter's Active Record library for database operations, you may need to retrieve the last inserted auto-incremented ID for an insert operation. This article explores possible ways to achieve this.
Problem
In your CodeIgniter application, you attempt to insert data into a MySQL table using Active Record's insert() method within a model. However, your code doesn't return the expected auto-incremented ID.
Solution
To retrieve the last inserted auto-incremented ID, follow these 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>
<code class="php">$this->db->trans_start(); $this->db->insert('posts', $post_data); $insert_id = $this->db->insert_id(); $this->db->trans_complete(); return $insert_id;</code>
Further Considerations
The above is the detailed content of How to Get the Auto-Incremented ID After Inserting Data with CodeIgniter's Active Record?. For more information, please follow other related articles on the PHP Chinese website!