Home > Database > Mysql Tutorial > How to Get the Last Inserted ID in CodeIgniter Active Record?

How to Get the Last Inserted ID in CodeIgniter Active Record?

DDD
Release: 2024-11-05 03:07:02
Original
944 people have browsed it

How to Get the Last Inserted ID in CodeIgniter Active Record?

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:

  1. $this->db->insert('posts', $post_data); executes the insert query and returns TRUE on success.
  2. $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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template