How to Get Last Inserted Id in CodeIgniter

On 7/27/2016

Hi! In this post let's see how to get last inserted id in codeigniter. While working with database systems, it's not uncommon for developers to require the last insert id from the database. By 'id' we mean the auto-incremented primary key of any table. Immediately after inserting a new record into db, you can get the id of the latest record. Similar to core PHP, codeigniter framework too provides a separate function to get last insert id after database insert operation.

How to Get Last Inserted ID in CodeIgniter?

To get last insert in codeigniter you have to use the function $this->db->insert_id(); which is part of the active record class library.

<?php
// get form data
$user = array(
    'name' => $this->input->post('txt_name'),
    'email' => $this->input->post('txt_email'),
    'password' => md5($this->input->post('txt_password')),
    'regdate' => date('Y-m-d H:i:s'),
    'status' => '1'
);

//insert into db
if ($this->db->insert('tbl_users', $user))
{
    //get last insert id
    return $this->db->insert_id();
}
return false;
?>

Above codeigniter snippet depicts the usage of db->insert_id(); function which inserts form data into database and get the last inserted id from it.

That explains about how to get last insert id in codeigniter. I hope you find this quick code igniter tutorial useful. See you in the next post!

1 comment:

Contact Form

Name

Email *

Message *