php pdo 遍历,转换PHP while循环以使用PDO

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?”了解部分故事.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值