1

How can I do this:

for ($i=0; $i<$number; $i++)
{
    mysql_query("INSERT INTO blah (foo, bar) VALUES (".$array[$i].", 1)");
}

With just one INSERT?

Is it possible?


PS: I know mysql_query is deprecated.

6
  • 2
    INSERT INTO blah(foo, bar) VALUES (...), (...), (...), (...), ... Commented Oct 5, 2015 at 16:11
  • If $number is not a known constant, it is impossible to do this without looping at some stage. Commented Oct 5, 2015 at 16:12
  • either you loop and run the query multiple times, or you loop to build up an extended-syntax insert query and then call it once. either way, you're looping. what you want is not possible WITHOUT loops. Commented Oct 5, 2015 at 16:13
  • @lad2025 Create an answer for me to accept. Thanks. Commented Oct 5, 2015 at 17:19
  • I'll update the question. My intent is not to make multiple Inserts. I want to use just 1 Insert. Commented Oct 5, 2015 at 17:20

2 Answers 2

1

You can pass multiple VALUES in INSERT statement like:

INSERT INTO blah(foo, bar) 
VALUES (...), (...), (...), (...),...
Sign up to request clarification or add additional context in comments.

Comments

0

You can do:

$stmt = "";

for ($i = 0; $i < $number; $i++) {
    $stmt .= "INSERT INTO blah (foo, bar) VALUES (" . $array[$i] . ", 1);";
}

//deprecated: mysql_multi_query($stmt);
mysqli_multi_query($stmt);

1 Comment

This way I'll still make multiple Inserts.

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.