Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hugowetterberg/388062 to your computer and use it in GitHub Desktop.
Save hugowetterberg/388062 to your computer and use it in GitHub Desktop.
<?php
$update = util_record_exists('table_name', $record);
drupal_write_record('table_name', $record, $update);
function util_record_exists($table, $record, $return_keys = TRUE) {
$schema = drupal_get_schema($table);
$sql = "SELECT COUNT({$schema['primary key'][0]}) FROM {{$table}} WHERE ";
$keys = array();
$params = array();
foreach ($schema['primary key'] as $key) {
$keys[] = $key . '=' . db_type_placeholder($schema['fields'][$key]['type']);
$params[] = $record[$key];
}
$sql .= join($keys, ' AND ');
$exists = db_result(db_query($sql, $params)) != FALSE;
$result = $exists;
if ($return_keys) {
$result = $exists ? $schema['primary key'] : array();
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment