Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7: fastest way to check if db entry exists

Tags:

drupal-7

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");
         }
like image 445
Bob Avatar asked Jun 23 '12 19:06

Bob


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 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.

like image 180
Web Assistant Avatar answered Nov 03 '22 06:11

Web Assistant


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());
like image 6
Juampy NR Avatar answered Nov 03 '22 06:11

Juampy NR