Skip to content

Instantly share code, notes, and snippets.

@jacobbednarz
Last active December 30, 2015 04:29
Show Gist options
  • Save jacobbednarz/7776749 to your computer and use it in GitHub Desktop.
Save jacobbednarz/7776749 to your computer and use it in GitHub Desktop.
Example of using drupal_write_record over a conditional db_insert and db_update.
<?php
// Let's say for argument sake $query is a database query that checks for the
// presence of an existing record and returns FALSE if nothing is found. In this
// example, we need to check for an existing record and update the row if it
// exists or create a new entry if it doesn't.
/**
* Bad
*/
if ($query == FALSE) {
$entry = db_insert('my_custom_module_table')
->fields(array(
'field_a' => 'one value',
'field_b' => 'another value',
'created' => REQUEST_TIME,
'changed' => REQUEST_TIME,
))
->execute();
}
else {
$entry = db_update('my_custom_module_table')
->fields(array(
'field_a' => 'one value',
'field_b' => 'another value',
'changed' => REQUEST_TIME,
))
->condition('uid', $query->uid, '=')
->range(0, 1)
->execute();
}
/**
* Good
*/
$entry_data = array(
'field_a' => 'one value',
'field_b' => 'another value',
'changed' => REQUEST_TIME,
);
if ($query == FALSE) {
$entry_data['created'] = REQUEST_TIME;
drupal_write_record('my_custom_module_table', $entry_data);
}
else {
drupal_write_record('my_custom_module_table', $entry_data, array('uid'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment