PHP手册中的标准文档通常非常有用.在PHP手册
PDO Details中有一个用PDO执行for循环的例子.
function getFruit($conn) {
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
通过一些更改,可以使用准备好的语句进行示例.
function getFruit($conn) {
$query = $conn->prepare('SELECT name, color, calories FROM fruit WHERE kind=:kind ORDER BY name');
$query->execute(array(':kind' => 'drupe'));
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
// this is dependent upon the design of your app
foreach ($query as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
您还可以使用while循环和PDOStatement::fetch来获取每一行.
function getFruit($conn) {
$query = $conn->prepare('SELECT name, color, calories FROM fruit WHERE kind=:kind ORDER BY name');
$query->execute(array(':kind' => 'drupe'));
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
// this is dependent upon the design of your app
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
PHP手册在提供创建后两个版本的所有必要信息方面仍然非常有用.
最后一个版本的解释:假设$conn是一个有效的PDO对象. $conn-> prepare($sql)如果成功则返回PDOStatement对象,失败时返回false或基于错误处理返回异常.因此,假设成功,我们希望实际从对象获取数据.我们可以在循环或$query->fetchAll()中使用$query->fetch()来获取取决于您的应用程序的数据.传入类常量PDO :: FETCH_ASSOC将返回,你猜对了,一个关联的数据数组.
从功能上讲,foreach和while实现是等效的.从概念上讲,foreach更合适,因为while循环具有循环的内涵,而静态条件成立,而foreach循环遍历集合的元素.阅读“Differences between a while loop and a for loop in PHP?”了解部分故事.