转换PHP while循环以使用PDO

Din*_*ino 7 php sql pdo

我正在通过切换到PDO来更新我的应用程序.我有以下代码:

$stmt = $db->prepare("select * from `product` where productid in (:productidLst)");
$stmt->bindParam(":productidLst",$productidLst, PDO::PARAM_INT);
$stmt->execute();
Run Code Online (Sandbox Code Playgroud)

在上面的代码之后,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;
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多组合,但没有成功,所以任何帮助这将是赞赏(在第二个代码块$ res是sql).其次我已将参数$ productidLst设置为INT这是正确的还是应该是字符串?

-------------------- UPDATE 1 ---------------------------- ------------------------

我试过以下代码:

$stmt = $db->prepare("select * from `product` where productid in (:productidLst)");
foreach ($stmt->execute(array(':productidLst' => $productidLst)) as $row) 
{
    $total += $row['total'];
}
Run Code Online (Sandbox Code Playgroud)

返回:为foreach()错误提供的参数无效

Rob*_*obB 16

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

通过一些更改,可以使用准备好的语句进行示例.

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用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";
    }
}
Run Code Online (Sandbox Code Playgroud)

PHP手册在提供创建后两个版本的所有必要信息方面仍然非常有用.

最后一个版本的说明:假设$conn是一个有效的PDO对象. 如果成功,失败基于错误处理的异常,则$conn->prepare($sql)返回PDOStatement对象.因此,假设成功,我们希望实际从对象获取数据.我们可以在循环中使用或获取取决于您的应用程序的数据.传入类常量将返回,你猜对了,一个关联的数据数组.false$query->fetch()$query->fetchAll()PDO::FETCH_ASSOC

在功能上,foreachwhile实现是等效的.从概念上讲,a foreach更合适,因为while循环具有循环的内涵,而静态条件成立,而foreach循环则集合的元素.部分故事请阅读" PHP中的while循环和for循环之间的差异? ".

一定要阅读关于PDOphp.net参考资料