欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

drupal db_query count get count with db_select 有大用

Hi,
is it possible to get number of results with db_select function?

Comments

Anonymous’s picture

The easiest way would be:

$results = db_select('table')->fields(NULL, array('field'))->execute()->fetchAll();$count = count($results);
Joel Costa’s picture

    $result = db_select('table_name', 'table_alias')
            ->fields('table_alias')
            ->execute();
    $num_of_results = $result->rowCount();
tomas.teicher’s picture

thank you both,
I think better is rowCount(),
but count() works too
thanks
Tomas

Joel Costa’s picture

The difference here is:

If you use count() you need to execute fetchAll() first, this means you need to get all data from your database first. So, if your result have 10.000 rows, than you will need to fetch it from your database and load into memory (assign it to a variable).

With rowCount() you don't need to fetch data from database, so it is more efficient.

drnikki’s picture

similarly, you can add an expression. See http://drupal.org/node/1266664

itqn2004’s picture

or

$countnode = db_query("SELECT COUNT(nid) AS count FROM {taxonomy_index} WHERE tid = :tid", array(':tid' => $tid))->fetchField();

http://jobs68.com
Build Drupal website please contact me itqn2004@gmail.com
TanTran

kunal.kursija’s picture

countQuery() with dynamic queries is also one of the way to acheive this.

$results = db_select('table')->fields(NULL, array('field'))->countQuery()->execute()->fetchField();print_r($results);
chrisroditis’s picture

This is 10x more resource efficient than using ->rowCount() after execute()

A healthy disregard for the impossible.

jeff h’s picture

This is the proper way. Be warned though—stupidly it returns the integer count as a string.

kalaiselvann’s picture

Hi

Get count with db_select working fine. In the below code:

$query = db_select('node', 'n')
      ->condition('n.type', 'article', '=')
      ->fields('n', array('nid','title'))
      ->execute();
      $num = $query->rowCount();

来自  https://www.drupal.org/forum/support/module-development-and-code-questions/2011-07-22/get-count-with...

普通分类: