How To Get Last Inserted Id In Codeigniter?

We require to get last insert record id from database in controller, so in this tutorial we will learn how to get last insert id in Codeigniter 3 project.

It very often needs to get last insert id in the programming field, if you are working on the Codeigniter framework and you want to fetch last created id, I mean max id, then you do easily. Codeigniter provides method insert_id() to get the last inserted id.

insert_id() is function of "DB" library. DB library provides several functions for connecting database tasks. insert_id() will return the id of last inserted record. So here I give the controller method so you can understand how it is working.

Write Controller Method
function add_user(){
   $input = ['name'=>'Test', 'email'=>''];

   $this->db->insert('users', $input);
   $insertId = $this->db->insert_id();

   return  $insertId;

use this code $this->db->insert_id(); and get last insert id in codeigniter

I hope it can help you...

  1. Thanks for sharing this wonderful information I really enjoyed reading it. Keep up the good work. If you have time, please visit our posts.

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!