Home > Database > Mysql Tutorial > body text

How to Retrieve the Last Inserted ID After an INSERT Query in CodeIgniter Active Record?

Linda Hamilton
Release: 2024-11-05 20:08:02
Original
227 people have browsed it

How to Retrieve the Last Inserted ID After an INSERT Query in CodeIgniter Active Record?

How to Retrieve the Last Inserted ID After an INSERT Query in CodeIgniter Active Record

Problem:

When executing an insert query using CodeIgniter's Active Record, you aim to retrieve the last auto-incremented ID for the inserted record. However, you encounter difficulties obtaining this value.

Solution:

To correctly retrieve the last inserted ID in CodeIgniter Active Record, follow these steps:

  1. Avoid Transacting Around the INSERT Operation:
    In your provided model function, you have wrapped the insert operation in a transaction using trans_start() and trans_complete(). For single-insert operations, this is unnecessary. Remove these transaction blocks to retrieve the last ID correctly.
  2. Call insert() Before insert_id():
    Once you have removed the transactions, ensure you call insert() before accessing insert_id().

Updated Model Function:

<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

For multiple inserts, consider using bulk inserts with batch statements.

The above is the detailed content of How to Retrieve the Last Inserted ID After an INSERT Query 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