0

I am trying to set up a database insert helper function for a group of modules for a program I m using to learn Drupal.

I can't figure out how to use my returned array in my db_insert query, can anyone assist please.

I assumed I could use a for loop as below but that's not working for me, I really appreciate any help you can offer

function my_db_insert($table, $fields) {

// Build up a string based on my returned array via a for loop   
$insert_fields="";
foreach ($fields as $key=>$value) {
    $insert_fields = $insert_fields . $key . "=>" . $value . ",";
      //drupal_set_message($key . "=>" . $value . ",");
   }

  // Insert into the database.
$id = db_insert($table)
->fields(array(
  //This is where I need put the result of my array so it will add to the database 
  $insert_fields
))
->execute();

return $id;

drupal_set_message(t("Record Added!"));


}
1

This was answered on the drupal.org forum by @Jaypan:

$id = db_insert($table)
  ->fields($fields)
  ->execute();
  • Thats generally true, but not in this case. I fat-fingered a downvote instead of an upvote, my apologies. Fixed now – Clive Jan 10 '17 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy