# using the shortcut ->query() method here since there are no variable
# values in the select statement.
$STH = $DBH->query('SELECT name, addr, city from folks');
# setting the fetch mode $STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
echo $row['name'] . "n";
echo $row['addr'] . "n";
echo $row['city'] . "n";
}
这个 while 循环将在获取完所有数据后停止.{The while loop will continue to go through the result set one row at a time until complete.}
FETCH_OBJ
这种模式为每一行数据创建一个标准类,下面是一个例子:
# creating the statement
$STH = $DBH->query('SELECT name, addr, city from folks');
# setting the fetch mode $STH->setFetchMode(PDO::FETCH_OBJ);
# showing the results
while($row = $STH->fetch()) {
echo $row->name . "n";
echo $row->addr . "n";
echo $row->city . "n";
}
FETCH_CLASS
您的对象的属性应该在constructor被调用前设置!这一点很重要!
这种模式允许你直接将获取的数据发送到您选择的类中.当您使用FETCH_CLASS时,您的对象的属性应该在constructor被调用前设置。读一遍,它是重要的。如果属性相匹配的列名不存在,这些属性将被创建,(公共)为您。
这意味着如果你需要转换后出来的数据,它可以通过你的对象自动为转换.
举个列子,假设的情况下该地址必须为特定格式,我们可以通过constructor上做到这一点,下面是一个例子:
class secret_person {
public $name;
public $addr;
public $city;
public $other_data;
function __construct($other = '') {
$this->address = preg_replace('/[a-z]/', 'x', $this->address);
$this->other_data = $other;
}
}



