是否有一种方法可以告诉Drupal 7中的SelectQuery结果中有多少行?


Is there a way to tell how many rows are in the SelectQuery results in Drupal 7?

我真正想知道的是我的查询是否返回结果,但是实际的行计数值会很好。

的例子:

$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title', 'status'));

你要找的人:

countQuery ()

在你的例子中,你可以使用:

$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title', 'status'));
$num_rows=$query->countQuery()->execute()->fetchField();

计算结果,然后取出结果:

$result=$query->execute();

您可以使用方便的查询fetchAll()方法将所有结果加载到一个数组中,然后按正常计数该数组。这将导致只执行一个查询:

$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title', 'status'));
$results = $query->execute()->fetchAll();
$count = count($results);
foreach ($results as $result) {
  // ...
}

我觉得这样更有效率。

$result = db_select('table_name' ,'t');
$result->fields('t')->execute();
$num_of_results = $result->rowCount();