Getting Last Inserted ID with CodeIgniter Active Record
Question:
In an insert query using CodeIgniter's Active Record, how can you retrieve the last auto-incremented ID after the insert operation?
Answer:
In the model method:
<code class="php">function add_post($post_data) {
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}</code>
Copy after login
Explanation:
- $this->db->insert('posts', $post_data); executes the insert query and returns TRUE on success.
- $this->db->insert_id(); retrieves the last inserted ID, which is the auto-incremented value generated for the new row.
Notes:
- If multiple rows are inserted in a single transaction (e.g., using $this->db->trans_start()...$this->db->trans_complete()), $this->db->insert_id() will return the ID of the last inserted row.
- Do not set an 'id' field in $post_data since auto-incrementing fields should not be manually assigned.
The above is the detailed content of How to Get the Last Inserted ID in CodeIgniter Active Record?. For more information, please follow other related articles on the PHP Chinese website!