Johanna Johanna - 17 days ago 4
PHP Question

Drupal 7 db_update with foreach loop

I have Drupal 7 site with a table

events_times
. I need to check to see if any of the records exist in the database. If they do I want to do an update not an insert. I have been tinkering with the code but cannot get it working. I am getting the following error:

Fatal error: Call to undefined method UpdateQuery::values()


Here is my code:

$times_values= array();

foreach ($form_state['values']['times_fieldset']['registration_times'] as $time) {
$times_values[] = array('event_id' => $eventId,
'registration_times' => $time,
'max_attendees' => 0
);
}
//Check to see if values exist in the table already
$exists = db_select('events_times','et')
->fields('et')
->condition('event_id',$event->id,'=')
->execute()
->fetchAll();

if ($exists == FALSE) {
$query = db_insert('events_times')->fields(array('event_id', 'registration_times', 'max_attendees'));
foreach ($times_values as $record) {
$query->values($record);
}
$query->execute();
}
else {
$query = db_update('events_times')->fields(array('event_id', 'registration_times', 'max_attendees'));
foreach ($times_values as $record) {
$query->values($record);
}
$query->execute();
}

Answer

Drupal's db_update() and db_insert() use the fields() method to define where your values should end up. To support multiple insert the insert object and also accept values through the values() method.

$query->fields(array(
  'registration_times' => $values['registration_times'],
);