drupal获取查询结果

论坛: 

因为drupal采用pdo作为底层数据库虚拟层,所以我们可以通过一下方法获取查询结果。

<?php
$result->fetch(); // 获取一行
$result->fetchAll(); // 获取全部,
$result->fetchObject(); // 以对象方式获取一行
$result->fetchAssoc(); // 以关联数组方式获取一行
$result->fetchColumn(); // 获取首列
$record = $result->fetchField($column_index);//返回指定列,默认为0
$number_of_rows = $result->rowCount();//返回结果总共有多少列
?>

更高级的使用:

<?php
检索所有记录到stdClass对象。
$result->fetchAll();

// 将制定的建检索到数组。
$result->fetchAllAssoc($field);

// 将结果集以列1=>列2的形式返回到数组。
$result->fetchAllKeyed();
// 你可以执行对应关系
$result->fetchAllKeyed(0,2); // 以 列 0 => 列 2 形式组合返回
$result->fetchAllKeyed(1,0); // 以 列 1 => 列 0 形式组合返回
$result->fetchAllKeyed(0,0); // 以 列 0 => 列 0 形式组合返回

// 检索一列返回,默认为第一列,既索引值为0的列
$result->fetchCol();
// 我们也可以指定列的索引值
$result->fetchCol($column_index);
?>

我们做些测试吧~

$str = db_select('block','b')
->fields('b')
->range(0,3)
->execute()
->fetchAll();
print_r($str);
//下面是返回结果
Array
(
[0] => Array
(
[bid] => 1
[module] => system
[delta] => main
[theme] => bartik
[status] => 1
[weight] => 0
[region] => content
[custom] => 0
[visibility] => 0
[pages] =>
[title] =>
[cache] => -1
)

[1] => Array
(
[bid] => 2
[module] => search
[delta] => form
[theme] => bartik
[status] => 1
[weight] => -1
[region] => sidebar_first
[custom] => 0
[visibility] => 0
[pages] =>
[title] =>
[cache] => -1
)

[2] => Array
(
[bid] => 3
[module] => node
[delta] => recent
[theme] => seven
[status] => 1
[weight] => 10
[region] => dashboard_main
[custom] => 0
[visibility] => 0
[pages] =>
[title] =>
[cache] => -1
)

)

$str = db_select('block','b')
->fields('b')
->range(0,3)
->execute()
->fetch();
print_r($str);
//下面是返回结果
Array
(
[bid] => 1
[module] => system
[delta] => main
[theme] => bartik
[status] => 1
[weight] => 0
[region] => content
[custom] => 0
[visibility] => 0
[pages] =>
[title] =>
[cache] => -1
)

$str = db_select('block','b')
->fields('b')
->range(0,3)
->execute()
->fetchObject();
print_r($str);
//下面是返回结果
Array
(
[bid] => 1
[module] => system
[delta] => main
[theme] => bartik
[status] => 1
[weight] => 0
[region] => content
[custom] => 0
[visibility] => 0
[pages] =>
[title] =>
[cache] => -1
)

$str = db_select('block','b')
->fields('b')
->range(0,3)
->execute()
->fetchAssoc();
print_r($str);
//下面是返回结果
Array
(
[bid] => 1
[module] => system
[delta] => main
[theme] => bartik
[status] => 1
[weight] => 0
[region] => content
[custom] => 0
[visibility] => 0
[pages] =>
[title] =>
[cache] => -1
)

$str = db_select('block','b')
->fields('b')
->range(0,3)
->execute()
->fetchColumn();
print_r($str);
//下面是返回结果

1