tags:

views:

80

answers:

3

How can I optimize this code?

$items[0] = "Item-0";
$items[1] = "Item-1";
$items[2] = "Item-2";
$items[3] = "Item-3";
...
$items[n] = "Item-n";

foreach($items as $item) {
    mysql_query("INSERT INTO mytable (item) VALUES ('$item')");
}

The array is just sample and the key point I like to know is how can I insert n items without querying n times?

Thanks.

+3  A: 

you can use mulitvalue insert statements

 insert into mytable(item) values('item1'),('item2') etc

http://dev.mysql.com/doc/refman/5.1/en/insert.html

stereofrog
+1  A: 
INSERT INTO `mytable` (`item`) VALUES ('value 1'), ('value 2'), ('value 3')

Form it using

$t = array("value 1", "value 2", "value 3");

$query = "('";
$query .= implode( "'), ('", $t);
$query .= "')";

echo $query;

Outputs ('value 1'), ('value 2'), ('value 3')

Now all you need to do is stick your original query into that output.

lemon
+1  A: 

stereofrog's answer is correct, however I wouldn't just built one massive query string.

After say 10 lots of values, I'd run an insert. It would seem less likely to fail that way then sending a possible huge query to MySQL

$query = '';

foreach($items as $key => $item) {

     if ($key % 10) {
        // Reset and insert
     }



}
alex