Home  >  Article  >  Database  >  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?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 20:08:02172browse

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>

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!

Statement:
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