CodeIgniter activerecord, retrieve last insert id?
To retrieve the last insert id in CodeIgniter using the Active Record class, you can use the $this->db->insert_id()
method. This method returns the id of the last inserted row.
Here is an example of how you can use it:
<?php
$data = [
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date',
];
$this->db->insert('mytable', $data);
$last_insert_id = $this->db->insert_id();
echo 'The last insert id is: ' . $last_insert_id;
Watch a video course
Learn object oriented PHP
Note:
- Make sure you have auto_increment field in your table.
- The
$this->db->insert_id()
method only works if you are using the MySQL database, and if the table you are inserting into has an AUTO_INCREMENT field.