CodeIgniter Forums
How do multiple inserts in database? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: How do multiple inserts in database? (/showthread.php?tid=11560)



How do multiple inserts in database? - El Forum - 09-13-2008

[eluser]Unknown[/eluser]
Hello, I can't do a multiple inserts in database from array.

The array $user['user'] is confromed like a list. No other data inside the array only the niks.

So I need insert that list in database.

I have:
Code:
$users = $_POST['users'];
$users = trim(strtolower($users));
$users = preg_replace("/[^a-z0-9, \"']/", '', $users);
$users = preg_replace("/,[^a-z0-9]*,/", ',', $users);
$users = rtrim($users, ',');
$users = explode(',', $users);
        
$this->load->model('add_users','', TRUE);
$this->add_users->insert_users($users);

Code:
function insert_users($users)
    {
        //INSERT USERs
        foreach ($users as $user):
        $data = array(
               'user_id' => 'NULL' ,
               'user_nick' => $user
            );

        $this->db->insert('table_users', $data);
        endforeach;
    }



How do multiple inserts in database? - El Forum - 09-13-2008

[eluser]Mirage[/eluser]
Sooo - what's the problem? Any errors?

-m


How do multiple inserts in database? - El Forum - 09-13-2008

[eluser]drewbee[/eluser]
Active record doesn't support inserting multiple records with one query. you have to loop over it each time and insert. Or just run a normal query if you are worried about performance and multiple inserts.


How do multiple inserts in database? - El Forum - 09-13-2008

[eluser]Unknown[/eluser]
It's solved x3.

Thanks anyway.

PD: It's possible insert multiple records with one query
Code:
foreach ($users as $user):
        $data = array(
               'image_id' => $id,
               'image_tag' => $user
            );

        $this->db->insert('table_users', $data);
        endforeach;



How do multiple inserts in database? - El Forum - 09-13-2008

[eluser]drewbee[/eluser]
Sorry. I didn't mean to confuse you. What your doing above is inserting multiple records with multiple inserts (multiple queries), not with one query. However if there are not that many records to insert and it doesn't happen all that often, this is just fine doing it this way. If you were worried about performance though that's when it would come into play.