0

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 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

1

user187291'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
     }



}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.