How to get last insert id from Database in Codeigniter?

Codeigniter Tutorials

In this Codeigniter Tutorial, I will let you know how to get last insert id from the table.

Sometimes, You have to work on relational tables where you perform the insert query on a table and you need that automatically generated ID to insert into second table to create relation between both tables.

In PHP, you can use mysqli_insert_id() function to get the last inserted ID.

In Codeigniter, You can use insert_id() function to get latest auto incremented column value from the MySQL table.

insert_id() is function of “db” library. There are numbers of query helper method in Codeigniter.

Syntax looks like this:

$data = array(					
	'Name' => 'Ishwar Acharya',
	'Phone' => 1234567890,
	'Address' => '3rd Floor, Abc Building, City-123456'			
);

$this->db->insert('table_name', $data);

$insertId = $this->db->insert_id();
return  $insertId;	// Returns last unique insert ID from table.

If you liked this article, then please subscribe to our YouTube Channel for useful videos. You can also find us on Twitter and Facebook.

About the author

Ishwar Acharya

I am a web designer and developer and keen on contributing to the web development industry since last 10 years. I love PHP development and absolutely amazed by front-end js libraries such as React, VueJs etc. Feel free to follow me @imishwaracharya on twitter.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *

No Comment

This post has not been commented yet.

The Webography