last insert id model codeigniter

To retrieve the last inserted ID using CodeIgniter, you can follow these steps:

  1. Load the database library: Before you can perform any database operations, you need to load the database library in CodeIgniter. You can do this by adding the following line of code to your controller or model:

php $this->load->database();

  1. Insert data into the database: Use the CodeIgniter's active record or query builder class to insert the data into the database. You can use functions like insert() or insert_batch() to perform the insertion. For example:

```php $data = array( 'name' => 'John Doe', 'email' => '[email protected]', 'phone' => '1234567890' );

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

In this example, we are inserting a new user record into the "users" table.

  1. Retrieve the last insert ID: After the data has been inserted, you can retrieve the last insert ID using the insert_id() method. For example:

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

The insert_id() method returns the ID of the last inserted row.

  1. Use the last insert ID: You can then use the last insert ID in your application as needed. For example, you can save it to another table that has a foreign key relationship with the inserted data, or display it to the user.

That's it! You have now retrieved the last insert ID using CodeIgniter. Remember to load the database library, insert the data, retrieve the last insert ID, and use it accordingly in your application.