How to get/return last inserted id in codeigniter?

Member

by lizzie , in category: PHP Frameworks , a year ago

How to get/return last inserted id in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a year 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' => 'john@example.com'
);

$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;


Related Threads:

How to get last inserted id in laravel?
How to get last inserted row in cakephp?
How to return last added id in laravel?
How to get the id of inserted row in laravel?
How to get session id in Codeigniter?
How to get id after insert in Codeigniter?