Retrieve the last insert id in CodeIgniter

Retrieve the last insert id in CodeIgniter

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Retrieving the Last Insert ID in CodeIgniter

When working with relational data, capturing the primary key of a newly created row is often a necessary step for subsequent operations, such as redirecting to an edit page or storing a reference in another table. In CodeIgniter, the database layer provides a straightforward mechanism to retrieve this value immediately after an insertion, but understanding exactly how it behaves prevents common logic errors.

The standard approach involves chaining the insert_id() method directly onto the result of the insert() call. When you invoke $this->db->insert(), it executes the SQL statement and returns a boolean indicating success or failure. If successful, you must explicitly access the generated ID from that result object. The correct syntax is:

$last_id = $this->db->insert('tablename', [
    'firstcolumn' => 'value', 
    'secondcolumn' => 'value'
]);

if ($last_id !== false) {
    // Access the ID from the result object, not the boolean directly
    $id = $last_id->insert_id();
    
    // Use $id for your next operations
}

It is crucial to distinguish between the return value of the insert() method and the actual ID. The insert() function returns a CI_DB_result object on success, not the integer ID itself. Attempting to use $this->db->insert_id() as a standalone method call without checking the result of the previous insert will fail or return null in many configurations because the method expects an active connection and a pending result context. By chaining the calls or storing the result, you ensure that CodeIgniter is looking at the most recent query execution to extract the LAST_INSERT_ID() value from the database driver.

Handling Auto-Increment Fields

In your specific scenario, the table has an id field configured as auto-increment. This means the database engine automatically generates a unique integer for every new row. The CodeIgniter abstraction handles the SQL translation correctly, but the retrieval method relies on the underlying MySQL or MariaDB driver to return the value set by the last insert operation.

If you are using a different database system like PostgreSQL, the behavior might differ slightly depending on the driver configuration, as PostgreSQL often requires RETURNING clauses or specific function calls to capture generated IDs reliably. However, for standard MySQL setups within CodeIgniter, the insert_id() method on the result object is the robust solution.

Trade-offs and Best Practices

While this direct chaining approach works well in many scenarios, there are important considerations regarding transaction safety and error handling. If you are wrapping your insert logic in a database transaction, ensure that you commit or roll back before attempting to retrieve the ID if your logic depends on it across multiple queries. In some high-concurrency environments, relying on LAST_INSERT_ID() immediately is safe because it is session-specific; however, if you are using connection pooling or switching contexts, verify that the connection state remains consistent.

Additionally, always validate the return value of the insert() call before accessing insert_id(). If the insert fails due to a unique constraint violation or a foreign key error, $last_id will be false, and calling insert_id() on a false value could lead to unexpected behavior depending on how your framework version handles it. Checking for truthiness first ensures your application doesn't attempt to redirect users based on a non-existent ID.

For developers looking for more advanced database interaction patterns or alternative frameworks that might simplify these specific retrieval needs, resources like the LaravelCompany blog often discuss similar persistence layer challenges with their own implementation details.

Our network