You are here

获得限制范围内的结果

g089h515r806 的头像
Submitted by g089h515r806 on 星期四, 2009-08-06 11:19

你可能会想,对于一个有很多日志条目的站点,比如说有10,000个,那么运行前面的代码将会非常危险。我们将对这个语句的结果进行限制,仅仅取回10个最新发布的日志:

$type = 'blog';
$status = 1; // In the node table, a status of 1 means published.
$sql = "SELECT * FROM {node} n WHERE type = '%s' AND status = %d ORDER BY
n.created DESC";
$result = db_query_range(db_rewrite_sql($sql), $type, $status, 0, 10);
while ($data = db_fetch_object($result)) {
    $node = node_load($data->nid);
    print node_view($node, TRUE);
}
    我们没有将语句传递给db_query()并使用LIMIT条件语句,在这里我们使用了函数db_query_range()。为什么呢?因为并非所有的数据库都支持LIMIT语法,所以我们需要使用db_query_range()作为包装函数。
    注意,我们将这些用来填充占位符的变量放在了范围的前面(也就是将type和status放在了0,10之前,如前面的例子所示)。
 

老葛的Drupal培训班 Think in Drupal

Drupal版本:

评论

g089h515r806 的头像

补充一下,出于习惯的问题,现在Drupal6中正确的顺序是

$result = db_query_range(db_rewrite_sql($sql), $type, $status, 0, 10);

 

下面的这个是不正确的:

$result = db_query_range(db_rewrite_sql($sql), 0, 10, NULL, $type, $status);
 

希望不要误解.最初drupal6中,后者可能是正确的,现在又改回去了. 参考http://api.drupal.org/api/function/db_query_range/6

How use this function in Drupal 6

-enzo- - Wed, 2010-02-24 19:37

Please note the order of arguments in Drupal 6 is switched around from what it is in Drupal 7

db_query_range($query, $args,$from, $count);

Enjoy it.

g089h515r806 的头像

后者是我最新实践所得,我按照$result = db_query_range(db_rewrite_sql($sql), 0, 10, NULL, $type, $status);尝试了很多次,总是有问题,没有想到参数的顺序有改回去了.标记一下,以免后来者出现同样的问题.