在Drupal中,我可以执行如下SQL:
$query_object = db_query("SELECT * FROM {nodes}");
Run Code Online (Sandbox Code Playgroud)
如果我知道查询只返回一个结果(所以只有1行和1列),我可以直接获取它:
$result = db_result($query_object);
Run Code Online (Sandbox Code Playgroud)
如果我得到了多个结果,我需要使用以下内容循环它们:
$rows[] = array();
while (($row = db_fetch_object($query_object) != FALSE) {
$rows[] = $row;
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更简单的方法吗?有没有办法可以将所有结果转换为带有单个语句的数组?或者不是那样工作,因为db_result返回一个类似游标的对象,每次只能获取一行?
Ber*_*dir 28
不在Drupal 6中.
在Drupal 7中,有一些fetch方法可以帮助避免这样的循环.来自http://drupal.org/node/310072:
<?php
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records into an associative array keyed by the field in the result specified.
$result->fetchAllAssoc($field);
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// You can also specify which two fields to use by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be field 0 => field 2
$result->fetchAllKeyed(1,0); // would be field 1 => field 0
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($column_index);
?>
Run Code Online (Sandbox Code Playgroud)
Jef*_*aes 18
在Drupal 7中,您还可以使用:
db_query('QUERY')->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17091 次 |
| 最近记录: |