Interface Testing Company India
Blazingcoders India helps our clients to make sure that their Web and Mobile application User Interface and User Experience is far above industry standards, capable to challenge even the most famous o
Read MoreSign Up Now and Get FREE CTO-level Consultation.
When working with databases in PHP CodeIgniter, one of the most common requirements is retrieving the ID of the record that was just inserted into a database table. Whether you're creating a user registration system, order management application, blog platform, or eCommerce website, getting the last inserted ID helps you connect related records efficiently.
Fortunately, CodeIgniter provides a simple and secure way to retrieve the last inserted ID after executing an INSERT query.
In this comprehensive guide, you'll learn how to get the last insert ID in PHP CodeIgniter, understand why it is important, explore different methods, review practical examples, and discover best practices for handling database insert operations.
The Last Insert ID refers to the auto-increment value generated by the database immediately after inserting a new record.
For example, suppose your users table contains the following data:
| ID | Name |
| 1 | John |
| 2 | David |
| 3 | Emma |
Now you insert a new user:
Name: Sophia
After insertion, the database automatically creates:
ID: 4
The value 4 is called the Last Insert ID.
Instead of manually querying the database again, CodeIgniter allows you to retrieve this value instantly.
Retrieving the last inserted ID is useful in many real-world applications.
Some common use cases include:
Creating user profiles after registration
Saving customer orders
Creating invoices
Uploading user documents
Saving product images
Managing blog posts and comments
Creating payment records
Storing shipping information
Linking parent and child tables
Without retrieving the insert ID, connecting related database records becomes much more difficult.
Most database tables use an AUTO_INCREMENT primary key.
Example table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(150)
);
Whenever a new record is inserted, MySQL automatically generates the next ID.
CodeIgniter simply retrieves that generated value.
In CodeIgniter 4, the easiest method is using:
$db->insertID();
$db = \Config\Database::connect();
$builder = $db->table('users');
$data = [
'name' => 'John',
'email' => '[email protected]'
];
$builder->insert($data);
$insertId = $db->insertID();
echo $insertId;
Output
1
This is the recommended method in CodeIgniter 4.
Suppose you're creating a registration system.
Controller:
public function register()
{
$db = \Config\Database::connect();
$builder = $db->table('users');
$data = [
'name' => 'Sophia',
'email' => '[email protected]'
];
$builder->insert($data);
$userId = $db->insertID();
echo "User ID : ".$userId;
}
After registration, the application immediately knows the user's database ID.
If you're using Models, the process becomes even cleaner.
Model:
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $allowedFields = ['name','email'];
}
Controller:
$model = new UserModel();
$model->insert([
'name'=>'David',
'email'=>'[email protected]'
]);
$id = $model->getInsertID();
echo $id;
Output
5
The getInsertID() function returns the ID of the newly inserted record.
If you're working with CodeIgniter 3, use:
$this->db->insert_id();
Example:
$data = array(
'name'=>'Alex',
'email'=>'[email protected]'
);
$this->db->insert('users',$data);
$id = $this->db->insert_id();
echo $id;
Output
8
This method works with MySQL and other supported database drivers.
When inserting multiple rows at once, remember that the returned ID is only the first generated ID.
Example:
$data = [
[
'name'=>'John'
],
[
'name'=>'David'
]
];
$builder->insertBatch($data);
Since multiple IDs are generated, retrieving all inserted IDs isn't directly supported.
This is one of the most common scenarios.
Suppose you're saving an order.
First insert the order.
$order = [
'customer_name'=>'Robert'
];
$builder = $db->table('orders');
$builder->insert($order);
$orderId = $db->insertID();
Now insert products.
$product = [
'order_id'=>$orderId,
'product'=>'Laptop'
];
$db->table('order_items')->insert($product);
Here the Order ID becomes the foreign key in the order_items table.
Imagine a product management system.
Insert product:
$product = [
'name'=>'Camera'
];
$db->table('products')->insert($product);
$productId = $db->insertID();
Now save image.
$image = [
'product_id'=>$productId,
'image'=>'camera.jpg'
];
$db->table('product_images')->insert($image);
This creates a proper relationship between the product and its images.
Transactions help keep your database consistent.
Example:
$db->transStart();
$db->table('users')->insert([
'name'=>'Alice'
]);
$userId = $db->insertID();
$db->table('profiles')->insert([
'user_id'=>$userId,
'city'=>'Chennai'
]);
$db->transComplete();
If any query fails, the transaction rolls back automatically.
Before retrieving the ID, always verify that the insert operation succeeded.
Example:
$result = $builder->insert($data);
if($result)
{
echo $db->insertID();
}
else
{
echo "Insert Failed";
}
This prevents unexpected errors.
Many beginners make these mistakes:
Wrong:
$id = $db->insertID();
$builder->insert($data);
Always call it after the insert query.
The insert and insertID() should use the same database connection.
Incorrect usage can return the wrong value.
It doesn't.
You'll need another approach if you require every generated ID.
For reliable database operations:
Always use Models whenever possible.
Validate user input before inserting.
Use transactions for related inserts.
Handle insert failures gracefully.
Keep database logic separate from controllers.
Avoid raw SQL when Query Builder can do the job.
Use prepared queries to improve security.
Maintain proper foreign key relationships.
Log database errors during development.
Test insert operations thoroughly.
To build efficient CodeIgniter applications:
Minimize unnecessary database queries.
Retrieve the insert ID immediately after insertion.
Use indexes on primary and foreign keys.
Optimize large insert operations.
Use batch inserts for importing data.
Avoid duplicate insert queries.
Enable database caching where appropriate.
Regularly optimize your database tables.
Retrieving the last insert ID is an essential skill for every PHP CodeIgniter developer. Whether you're building a simple CRUD application or a complex enterprise solution, knowing the ID of the newly inserted record allows you to create relationships between tables, manage user data, process orders, and store related information efficiently.
CodeIgniter makes this task straightforward with methods like insertID(), getInsertID(), and insert_id() depending on the framework version. By following the best practices discussed in this guide—such as validating data, using transactions, checking insert success, and maintaining clean database architecture—you can build secure, scalable, and high-performing web applications.
If you're looking to develop a custom PHP CodeIgniter application, CRM, ERP system, eCommerce platform, or enterprise web solution, Blazingcoders offers expert PHP and CodeIgniter development services tailored to your business needs. Our experienced developers build fast, secure, and scalable web applications using the latest development standards and best practices.
Use:
$db->insertID();
or
$model->getInsertID();
Use:
$this->db->insert_id();
Yes. CodeIgniter Models provide the getInsertID() method immediately after an insert operation.
Yes. It works perfectly with MySQL and other supported database systems that generate auto-increment IDs.
No. CodeIgniter does not return all generated IDs after batch insertion. You will need an alternative strategy if you require every inserted ID.
Yes. It is commonly used within database transactions to link parent and child records securely.
Request a FREE Business Plan.
+91 ▼ Blazingcoders India helps our clients to make sure that their Web and Mobile application User Interface and User Experience is far above industry standards, capable to challenge even the most famous o
Read More
If you own a business, website, or personal brand, using an email address such as [email protected] looks more professional than using a generic Gmail address. The good news is that you can use Gmail
Read More
Animation is becoming a crucial tool for branding, marketing, education, and other fields in today's digital age. Blazingcoders is a top 2D animation development company in India that specializes
Read More