How to get/return last inserted id in codeigniter?

Member

by lizzie , in category: PHP Frameworks , 7 months ago

How to get/return last inserted id in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 7 months ago

@lizzie 

To get the last inserted ID in CodeIgniter, you can use the $this->db->insert_id() method after inserting data into the database. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$data = array(
    'name' => 'John',
    'email' => '[email protected]'
);

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

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

echo "Last inserted ID: " . $inserted_id;


This code snippet inserts a new record into the users table and then retrieves the last inserted ID using the $this->db->insert_id() method.


You can also return the last inserted ID from a model function by returning the value of insert_id() like this:

1
2
3
4
5
public function save_user($data) {
    $this->db->insert('users', $data);

    return $this->db->insert_id();
}


You can then call this function from your controller and access the last inserted ID like this:

1
2
3
$inserted_id = $this->your_model->save_user($data);

echo "Last inserted ID: " . $inserted_id;