Is there any way to get last inserted IDs from batch inserts in codeigniter ?
This might seem silly but I wonder if there is any help available.
Is there any way to get last inserted IDs from batch inserts in codeigniter ?
This might seem silly but I wonder if there is any help available.
You're gonna need to run the inserts in a loop, that's the only way to get each of the IDs. To lessen the strain on the server, you can do this inside of a transaction.
$ids = array();
$this->db->trans_start();
foreach($data as $val){
$this->db->insert('yourTable', array(
'field1' => $val['foo'],
'field2' => $val['bar']
));
$ids[] = $this->db->insert_id();
}
$this->db->trans_complete();
Since $this->db->insert_id();
should return the ID of the first row from the batch, you can just add the number of affected rows to it. But of course, assuming that's possible because you're using auto-increment.
As Rocket Hazmat pointed out, there could be variations in auto-increment values. However, that's not a problem if we know the increment value. So, something like this should work:
$increment = 2; // auto-increment value (probably 1 though)
$id = $this->db->insert_id(); // id of the first inserted row from the batch
$total = $this->db->affected_rows(); // number of inserted rows
$ids = array($id); // add the first on to our output array of ids
for ($i = 1; $i < $total; $i += $increment) {
$ids[] = $id + $i; // add each of them
}