Home > Database > Mysql Tutorial > How to Retrieve the Last Auto-Incremented ID After an Insert Operation in CodeIgniter Active Record?

How to Retrieve the Last Auto-Incremented ID After an Insert Operation in CodeIgniter Active Record?

Mary-Kate Olsen
Release: 2024-11-04 22:17:02
Original
840 people have browsed it

How to Retrieve the Last Auto-Incremented ID After an Insert Operation in CodeIgniter Active Record?

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>
Copy after login

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>
Copy after login

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:

  1. Perform the insert operation first, using the $this->db->insert('posts', $post_data) method.
  2. Then, retrieve the last inserted ID using the $this->db->insert_id() method.
  3. Return the last inserted ID as the result of the add_post() method.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template