Codeigniter 2.1 - return ids after insert batch
codeigniter, php
Solution
Here is an efficient method:
Since your records have result ID's, I'm going to assume they also auto-increment.
If this is the case, you do this and still use insert_batch.
Here is what you do:
1. You take a count of the items you are inserting:
$count = count($data);
2. Run your batch insert:
$this->db->insert_batch($table, $data);
3. Get the first inserted ID of your batch:
$first_id = $this->db->insert_id();
4. Add the count (minus 1) to your insert ID to get the last records ID.
$last_id = $first_id + ($count-1);
There you go! You now have first and last ID's of your inserted records, and by extension, everything else in between.
Note:
A few people have asked what might happen if two batch inserts happen simultaneously; InnoDB will intelligently manage the ID's of the new rows to prevent the data intersecting, thus keeping this method valid.
Problem
How can I return all IDs after insert_bunch? Function: ``` public function insert_slike($id, $slike, $folder, $polje, $tabela) { $slike = explode(',', $slike); $i = 1; $data = array(); foreach ($slike as $slk) { $this->img_upload_resize($slk, $folder); $data[] = array( $polje => $id, 'path' => $slk ); $i++; } $this->db->insert_batch($tabela, $data); } ```