How to Get Last Inserted Id using Codeigniter Active Record

How to Get Last Inserted Id using Codeigniter Active Record

Sometime we need last inserted id in the application to insert id to another table to make relations. Suppose we have a table of employee and another table is for
employee contact details. when creating new employee, its needed to insert that employee id in another table of employee contact details so that when we show employee information
It will helpful to join the ids from both table. Here we will see how to achieve this using codeigniter active record.Let see with an example.

1. In the controller we will get all information and save it to separate tables.The first information is for employee details.see below.

$dataEmployee = array(
'firstname' => $this->input->post('firstname'),
'middlename' => $this->input->post('middlename'),
'lastname' => $this->input->post('lastname'),
'phone' => $this->input->post('phone'),
'email' => $this->input->post('email')

2. Second is for employee contact details.After inserted employee details the last id need to insert with employee contact details.

$dataEmpContact = array(
'empid' => $querySaveEmployee,
'address' => $this->input->post('address'),
'state' => $this->input->post('state'),
'pincode' => $this->input->post('pincode'),
'city' => $this->input->post('city')
$querySaveEmployeeContacts = $this->employee_model->save_employee_contacts($dataEmpContact);

3. Below is the model function shows how to return last inserted id after inserting employee record

public function create_employee($dataEmployee)
$this->db->insert('employee', $dataEmployee);
$lastId = $this->db->insert_id(); /* get last inserted id */
return lastId;

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!