Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter 2.1 - return ids after insert batch

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);
}
like image 675
Sasha Avatar asked Mar 28 '13 14:03

Sasha


2 Answers

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.

like image 63
Platinum Fire Avatar answered Sep 25 '22 21:09

Platinum Fire


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.

like image 39
Marc Audet Avatar answered Sep 21 '22 21:09

Marc Audet