how i can fastest check, if db entry exists? i use this code:
$exists = db_query('SELECT tid FROM {taxonomy_index} WHERE tid = 1 AND nid = 1 LIMIT 1');
if($exists->rowCount() > 0){
drupal_set_message("exists");
}
I would do:
$result = db_select('taxonomy_index', 'ti')
->fields('ti', array('tid'))
->condition('tid', 1)
->condition('nid', 1)
->range(0, 1)
->execute()
->rowCount();
if ($result) {
drupal_set_message(t('Exists'));
}
Not related to your question, but you should always use placeholders to guard against SQL Injection - though if you use the query builder like above then it takes care of that for you. Also, you should always use the t() function when writing text to screen.
db_select()
is way slower than db_query()
. See this thread for scenarios where db_select()
fits better than db_query()
.
db_query()->fetchField()
is the simplest approach. See the following snippet:
// Returns string(5) "admin"
var_dump(db_query('select name from {users} where uid = 1')->fetchField());
// Returns bool(false)
var_dump(db_query('select name from {users} where uid = -1')->fetchField());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With