How to get insert id after save to database in CodeIgniter 4

How to get insert id after save to database in CodeIgniter 4

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

Stefan Bogdanescu

Founder & Senior Architect

Retrieving Generated IDs in CodeIgniter 4 Models

When you use the save() method on a CodeIgniter 4 model to insert new data, the framework handles the SQL execution internally. By default, this operation returns a boolean value indicating success or failure, but it does not automatically expose the primary key generated by the database. If your application logic depends on that ID immediately after insertion—perhaps to redirect a user, pass it in a JSON response, or store it in a session—you need to explicitly retrieve it.

CodeIgniter 4 provides a specific property on the model instance designed for this exact purpose: $insertID. However, accessing this value requires understanding how the framework's query builder interacts with the database layer and ensuring you are querying the correct connection.

Accessing the Insert ID Property

The most direct way to obtain the generated ID is by referencing the insertID property on your model instance. This property is populated automatically after a successful insert operation that affects rows in a table configured to return auto-incremented primary keys.

Consider a scenario where you are creating a new user record:

$data = [
    'username' => 'darth',
    'email'    => 'd.vader@theempire.com'
];

$userModel->save($data);

// Retrieve the generated ID
$newUserId = $userModel->insertID;

In this example, $newUserId will contain the integer value of the primary key assigned by your database engine (MySQL, PostgreSQL, etc.) immediately following the save() call. This approach works because CodeIgniter's Query Builder captures the result of the executed SQL statement and stores the affected rows count along with the last inserted ID in its internal state.

Handling Multiple Database Connections

If your application utilizes multiple database connections, you must ensure that the insertID property corresponds to the connection used by your model. CodeIgniter models are tied to specific database groups defined in your .env file and configuration. By default, models use the default database group.

If you have configured a custom connection group for your user table, say users_db, you should explicitly set that connection on the model instance before calling save(). Failure to do so might result in retrieving the insert ID from a different (and potentially empty) connection context, leading to incorrect values or errors if the property is accessed prematurely.

$userModel->setDBGroup('users_db'); // Ensure correct connection context
$userModel->save($data);
$newUserId = $userModel->insertID;

Troubleshooting Empty Results

A common pitfall occurs when attempting to read $insertID before confirming that the insert actually succeeded. If the save() method returns false, it means no rows were inserted, and consequently, the insertID property will either be null or contain data from a previous operation within the same script execution.

Always check the return value of the save() call:

if ($userModel->save($data)) {
    $newUserId = $userModel->insertID;
    // Proceed with logic using $newUserId
} else {
    // Handle error or log message
}

Additionally, ensure your database table has an auto-incrementing primary key defined. If the column is not set to AUTO_INCREMENT (or equivalent in other SQL dialects), the database will not generate a new ID, and CodeIgniter cannot retrieve one regardless of the method used.

Alternative Approaches for Complex Scenarios

In cases where you need to execute raw queries outside the standard model save mechanism, or if you are working with non-standard primary key configurations, you might need to query the database directly using the connection instance. This is less common in typical MVC workflows but necessary when dealing with legacy codebases or specific sharding strategies. For standard application development, however, relying on the model's $insertID property remains the most efficient and readable solution.

For developers looking to transition between frameworks or explore similar patterns in other PHP ecosystems, understanding how query builders manage transactional state is crucial. While CodeIgniter 4 handles this internally, the underlying principle mirrors approaches seen in Laravel, where accessing generated IDs follows a consistent pattern of inspecting the last executed query's result set.

If you are building complex enterprise applications requiring robust ORM features or need to integrate with specific third-party libraries that manage database state differently, checking out resources like https://laravelcompany.com can provide insights into how modern PHP frameworks handle these foundational concepts.

Our network