4

I'm trying to update someone's module to D7, but I'm unsure of how to convert the usage of places and values in the query to use 7's api properly.

$fields = implode(',', array_keys($args));
$places = implode(',', array_fill(0, count($args), "'%s'"));
$values = array_values($args);

$insert_result = db_query(
  'INSERT INTO {bluga_request}(' . $fields . ') VALUES (' . $places . ')', $values
);
5

The standard way is to use the db_insert() function with an associative array of field names/values:

$fields = array(
  'id' => $id,
  'name' => $name
);

db_insert('bluga_request')->fields($fields)->execute();

It actually looks like in your case the fields are already set up as an associative array in $args so you would just do this:

db_insert('bluga_request')->fields($args)->execute();
| improve this answer | |
  • that would work, but I'm not sure what VALUES (' . $places . ')', $values does can you explain that part so that I can adjust the $fields array? – Arosboro Mar 17 '12 at 20:26
  • At the moment your code is splitting up an associative array into two comma separated strings (one for field names, one for values)...this is done so it can be inserted directly into the SQL query string. Using the query builder you don't have to do this, you can just pass your original $args associative array to the ->fields() method. The updated answer has a code example :) – Clive Mar 17 '12 at 20:29
  • p.s. $places refers to a comma separated list of placeholders (%s) which were used in Drupal 6 to perform string replacement for the arguments in the query – Clive Mar 17 '12 at 20:31
  • @Arosboro Suppose $fields contains two items; then, $places will contain "'%s','%s'". If $fields contains six items, then $places will contain "'%s','%s','%s','%s','%s','%s','%s'". – kiamlaluno Mar 17 '12 at 20:36

Your Answer

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

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