Last active
December 30, 2015 04:29
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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