This is not possible with prepared instructions.
If you want to insert a variable number of records in one query, then the SQL query must be generated dynamically, which makes it impossible to prepare it beforehand.
If you use the database driver function escape_string (which would be quote() for MySQL), you can create a query and still receive the security information that the instructions prepared.
$query = "INSERT INTO table (a, b, c) VALUES"; $tuple = " ('%s', '%s', '%s'),"; foreach ($items as $item) { $a = $db->quote($item['a']); $b = $db->quote($item['b']); $c = $db->quote($item['c']); $query .= sprintf($tuple, $a, $b, $c); } $query = rtrim($query, ",");
Addendum:
If you use prepared instructions, you can insert records separately and not worry about pasting them at a time. This is actually the whole point of the prepared statement.
Unlike the old old SQL queries, which are a one-step process and are simply sent and then forgotten ...
$db->query("INSERT INTO table (a, b, c) VALUES ('a', 'b', 'c')");
... prepared statements are a two-step process.
First you create a prepared statement. This statement is then sent to the database, telling it that "this is what you expect." The database often also optimizes the query to make it faster. This step then returns you an instruction handle (often called $stmt in the PHP documentation).
$stmt = $db->prepare('INSERT INTO table (a, b, c) VALUES (:a, :b, :c)');
Secondly, with this descriptor you can go to the insert:
foreach ($records as $record) { $stmt->execute(array( ':a' => $record['a'], ':b' => $record['b'], ':c' => $record['c'], )); }
Since the database already knows what to expect, it can optimize INSERT s speed, which means that you do not need to go through the material mentioned above in this appendix.
Wikipedia has a pretty nice record of ready-made statements.