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);
}
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.
This topic with respect to MySQL has been previously discussed:
How can I Insert many rows into a MySQL table and return the new IDs?
In CodeIgniter, using $this->db->insert_id()
will return only id of the first insert.
If I were doing this, I would open a transaction and do the inserts one at at time, storing the id after each insert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With