Get the Lastest Inserted ID in CodeIgniter

Retrieving the id of the latest inserted record is a common task. We need to use the id for other related tables.

CodeIgniter’s Query Builder class offers a simple method to get the latest id.

We only need to call $this->db->insert_id().

$this->db->set('username', 'tltemplates');
$this->db->set('password', 'hashedpass');
$this->db->set('firtsname', 'Green');
$inserted = $this->db->insert($this->table_quote);
if($inserted){
	$last_id = $this->db->insert_id();
}

$data = array(
    'title' => 'My title',
    'content' => 'My content'
);

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

$insert_id = $this->db->insert_id();

echo $insert_id;

You can use this ID for further operations, such as updating or deleting the newly inserted row.

Leave a Comment

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


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close