Getting the Last Auto-Incremented ID with CodeIgniter Active Record
Question:
You're trying to retrieve the last auto-incremented ID after performing an insert operation using CodeIgniter's Active Record, but the add_post() method in your model returns an empty value.
Inside the Controller:
<code class="php">function add_post(){ $post_data = array( 'id' => '', 'user_id' => '11330', 'content' => $this->input->post('poster_textarea'), 'date_time' => date("Y-m-d H:i:s"), 'status' => '1' ); return $this->blog_model->add_post($post_data); }</code>
Inside the Model:
<code class="php">function add_post($post_data){ $this->db->trans_start(); $this->db->insert('posts',$post_data); $this->db->trans_complete(); return $this->db->insert_id(); }</code>
Answer:
The problem lies in the order of operations in your add_post() method in the model. To correctly retrieve the last auto-incremented ID after the insert operation, you need to:
Solution:
<code class="php">function add_post($post_data){ $this->db->insert('posts', $post_data); $insert_id = $this->db->insert_id(); return $insert_id; }</code>
Note:
If you're performing multiple inserts in a single transaction, you can use the $this->db->trans_start() and $this->db->trans_complete() methods to begin and end the transaction.
The above is the detailed content of How to Retrieve the Last Auto-Incremented ID After an Insert Operation in CodeIgniter Active Record?. For more information, please follow other related articles on the PHP Chinese website!