最常用的就是使用foreach()循环,对结果集进行迭代处理。
<?php
$result = db_query("SELECT nid, title FROM {node}");
foreach ($result as $record) {
// Do something with each $record
}
?>
由于所需返回结果的不同,除此以外,还有其它一些方式来获取记录。
为了明确的获取下一条记录,可以使用:
<?php
$record = $result->fetch(); // Use the default fetch mode.
$record = $result->fetchObject(); // Fetch as a stdClass object.
$record = $result->fetchAssoc(); // Fetch as an associative array.
?>
如果没有下一条记录,此时则返回FALSE。通常情况下,应该尽可能的避免使用fetch(),而是选择fetchObject()和fetchAssoc(),后两个语义明确,便于理解。如果你需要使用PDO所支持的其它获取模式,则可以使用fetch()。
为了从结果集中获取单个字段,可以使用:
<?php
$record = $result->fetchField($column_index);
?>
$column_index的默认值为0,表示第一个字段。
为了计算返回记录的总数,可以使用:
<?php
$number_of_rows = $result->rowCount();
?>
为了将所有记录放在单个数组中,可以使用下面的任意一种方式:
<?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);
?>
注意,fetchAll() 和fetchAllAssoc()在默认情况下,使用在查询上设置的获取模式(数值数组、关联数组、或对象)。通过向其传递一个新的获取模式常量,就可以修改默认的获取模式了。对于fetchAll(),它是第一个参数。对于fetchAllAssoc(),它是第二个参数。
由于PHP 支持对返回的对象调用链式方法,所以通常情况下,会完全跳过$result变量,采用下面的简洁方式:
<?php
// Get an associative array of nids to titles.
$nodes = db_query("SELECT nid, title FROM {node}")->fetchAllKeyed();
// Get a single record out of the database.
$node = db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchObject();
// Get a single value out of the database.
$title = db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchField();
?>