Insert large amount of rows from array to database with PHP and MySQL

This is how you can insert a large amount of rows from an array in PHP using only one call to MySQL instead of doing a loop with foreach and call MySQL for every row.

Note: db_query() is for Drupal, but the basic concept works in plain PHP/MySQL:

INSERT INTO parser_queue (sid, nid) SELECT id AS sid, 109 AS nid FROM source_109 WHERE id IN (1,2,3);

 

<?php
function db_parser_queue_insert($nid, $nids){
   
//note that the order of "sid, nid" is important, it has to be the same in both INSERT and SELECT parts
   
return db_query("INSERT INTO parser_queue (sid, nid) SELECT id AS sid, ".$nid." AS nid FROM source_".$nid." WHERE id IN (%s);", implode(",",$nids));
}
?>
Knowledge keywords: