Drupal 7: the fastest way to check if a db record exists

How can I check if a db record exists? I am using 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");
         }
+5
source share
2 answers

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 your question, but you should always use placeholders to protect against SQL Injection - although if you use the query builder as described above, it will take care of it for you. In addition, you should always use the t () function when writing text to the screen.

+8
source

db_select () is slower than db_query (). See this thread for scenarios where db_select () is better than db_query ().

db_query () → fetchField () is the easiest approach. See the following snippet:

<?php

// 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());

</pre>
+6
source

All Articles