我目前正在通过切换到 PDO 来更新我的应用程序。我有以下代码:
$stmt = $db->prepare("select * from `product` where productid in (:productidLst)");
$stmt->bindParam(":productidLst",$productidLst, PDO::PARAM_INT);
$stmt->execute();
在上面的代码之后 var $productidLst 是 1,2 我想使用 PDO 等效于此:
while($rs=mysql_fetch_assoc($res)){
$rs['qty']=$_SESSION['basket'][$rs['productid']];
$rs['total'] += $rs['qty']*$rs['price'];
$total += $rs['total'];
$a[] = $rs;
}
我已经尝试了很多组合,但都没有成功,所以任何帮助都将不胜感激(在第二个代码块 $res 中是 sql)。其次,我将参数 $productidLst 设置为 INT 这是正确的还是应该是一个字符串?
--------------------更新 1------------------------ ----------------------------
我试过下面的代码:
$stmt = $db->prepare("select * from `product` where productid in (:productidLst)");
foreach ($stmt->execute(array(':productidLst' => $productidLst)) as $row)
{
$total += $row['total'];
}
返回:为 foreach() 错误提供的参数无效
最佳答案
PHP 手册中的标准文档通常很有帮助。 PHP 手册中有一个使用 PDO 执行 for 循环的示例,PDO Details .
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->fetch()
在循环中或 $query->fetchAll()
获取依赖于您的应用程序的数据。传入类常量 PDO::FETCH_ASSOC
将返回,您猜对了,一个关联数据数组。
在功能上,foreach
和while
实现是等效的。从概念上讲,foreach
更合适,因为 while
循环具有在静态条件成立时循环的含义,而 foreach
循环遍历 a 的元素收藏。阅读“Differences between a while loop and a for loop in PHP?”部分故事。
请务必阅读 php.net reference on PDO
关于php - 将 PHP while 循环转换为使用 PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7043456/