Rafael
Rafael

Reputation: 634

Insert different values in array in MySQL in the same columns with just 1 insert

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.

Upvotes: 1

Views: 337

Answers (2)

Lukasz Szozda
Lukasz Szozda

Reputation: 175756

You can pass multiple VALUES in INSERT statement like:

INSERT INTO blah(foo, bar) 
VALUES (...), (...), (...), (...),...

Upvotes: 1

Jeroen Flamman
Jeroen Flamman

Reputation: 965

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);

Upvotes: 0

Related Questions