I am struggling to sort out how to insert a lot of records using db_insert

Please see below for the code.

I can't have a for loop in the array. It breaks but I am dealing with looping through a lot of data. 48 (states) X 365 (# days) X 36 years.

What is the best way of accomplishing this?


$query = db_insert('HDD')
  for ($s = 0; $s <= $cnt; $s++) {
    'HDDDAYS' => $time, //Loops through the dates
    'AL'=> $output1[$sts[0]][$dts[$s]],
    'AR'=> $output1[$sts[1]][$dts[$s]],
    'AZ'=> $output1[$sts[2]][$dts[$s]],
    'CA'=> $output1[$sts[3]][$dts[$s]],
    'CO'=> $output1[$sts[4]][$dts[$s]],
    'CT'=> $output1[$sts[5]][$dts[$s]],
    'DE'=> $output1[$sts[6]][$dts[$s]],
    'FL'=> $output1[$sts[7]][$dts[$s]],
    'WI'=> $output1[$sts[45]][$dts[$s]],
    'WV'=> $output1[$sts[46]][$dts[$s]],
    'WY'=> $output1[$sts[47]][$dts[$s]]

1 Answer 1


You could define your query fields first, then set your field values in a loop before executing the query.

Example (not tested):

$query = db_insert('HDD')->fields(array(

for ($s = 0; $s <= $cnt; $s++) {
    'HDDDAYS' => $time,
    'AL' => $output1[$sts[0]][$dts[$s]],
    'AR' => $output1[$sts[1]][$dts[$s]],


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.