将PHP while循环转换为使用PDO

问题描述:

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

I'm currently updating my app by switching to PDO. I have the following code:

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

在上面的代码之后,var $ productidLst为1,2,我想使用与此等效的PDO:

The var $productidLst is 1,2 after the above code I would like to use the PDO equivalent of this:

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是否正确或应该是字符串?

I have tried numerous combinations but not been successful so any help with this would be appreciated (in the 2nd code block $res was the sql). Secondly I have set the Parameter $productidLst to INT is this correct or should it be a string?

--------------------更新1 ------------------------- ---------------------------

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

我尝试了以下代码:

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

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

Which returns: Invalid argument supplied for foreach() error

PHP手册中的标准文档通常非常有用. PHP手册中有一个使用PDO执行for循环的示例, PDO详细信息.

The standard documentation in the PHP manual is usually pretty helpful. There is an example of executing a for loop with PDO in the PHP manual, 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";
    }
}

稍作更改,就可以使示例使用准备好的语句.

With a few changes, the example can be made to use a prepared statement.

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 来获取每一行. /p>

You can also use a while loop and PDOStatement::fetch to get each row.

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手册在提供创建后两个版本的所有必要信息方面仍然非常有帮助.

The PHP manual remains quite helpful in providing all the necessary information to create the latter two versions.

最后一个版本的说明:假定$conn是有效的PDO对象. $conn->prepare($sql)如果成功,则返回 PDOStatement 对象,发生故障时 OR 根据您的错误处理情况而产生的异常.因此,假设成功,我们实际上希望从对象中获取数据.我们可以循环使用 $query->fetch() $query->fetchAll() 来获取依赖于您应用程序的数据.您猜对了,传入类常量PDO::FETCH_ASSOC将返回一个关联的数据数组.

Explanation of the last version: assuming $conn is a valid PDO object. $conn->prepare($sql) returns a PDOStatement object if successful, false on failure OR an exception based on your error handling. So, assuming success we would want to actually get the data from the object. We can use $query->fetch() in a loop or $query->fetchAll() to get the data dependent upon your app. Passing in the class constant PDO::FETCH_ASSOC will return, you guessed it, an associative array of data.

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

Functionally, the foreach and while implementations are equivalent. Conceptually, a foreach is more appropriate, as a while loop has connotations of looping while a static condition holds, whereas foreach loops over elements of a collection. Read "Differences between a while loop and a for loop in PHP?" for part of the story.

请务必阅读PDO上的 php.net参考

Be sure to read the php.net reference on PDO