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'=>'abc@xyz.com'];

   $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...

Leave a Reply

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

We'll share your Website Only Trusted.!!