Reputation: 199
Model:
$data = array( 'firstname' => $fname,
'lastname' => $lname );
$result = $this->db->insert('users',$data);
Say that code inserted a new row. On the table, i have 3 columns, id,username,pass. The id is auto incremented. After inserting, how would i be able to retrieve the id of that newly inserted row. Assuming that i am inserting atleast 2 rows and with the same firstname or last name.
This is what im planning, im not sure yet if it will work.
$sql = $this->db
->select('id')
->where(' ', $variable)
->from('user')
->get()
->result_array();
Im not sure what to put on my where clause since it may have rows with the same firstname and last names. I need to get the auto incremented id of my newly inserted row. The id is also my PK.
Upvotes: 1
Views: 680
Reputation: 4527
You can get it by usingL $this->db->insert_id();
$result = $this->db->insert('users',$data);
$latest_id = $this->db->insert_id();
Read more ate Query Helpers
But if you are inserting multiple files using insert_batch()
this will not work, it will only get the last inserted id from the batch.SO if you are planning to insert multiple data you need a forloop
then do the normal insert while saving the inserted key in array sample
foreach($data as $v)
{
//prep data colum name as key ,value as value
$input['firstname'] = $v->firstname;
$input['lastname'] = $v->lastname;
//insert
$this->db->insert('users',$input);
//store keys in array
$inserted_ids[] = $this->db->insert_id();
}
print_r($inserted_ids);
Upvotes: 2