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();
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;
}
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?
——————–UPDATE 1—————————————————-
I have tried the following code:
$stmt = $db->prepare("select * from `product` where productid in (:productidLst)");
foreach ($stmt->execute(array(':productidLst' => $productidLst)) as $row)
{
$total += $row['total'];
}
Which returns: Invalid argument supplied for foreach() error
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.
With a few changes, the example can be made to use a prepared statement.
You can also use a
whileloop andPDOStatement::fetchto get each row.The PHP manual remains quite helpful in providing all the necessary information to create the latter two versions.
Explanation of the last version: assuming
$connis a valid PDO object.$conn->prepare($sql)returns aPDOStatementobject if successful,falseon 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 constantPDO::FETCH_ASSOCwill return, you guessed it, an associative array of data.Functionally, the
foreachandwhileimplementations are equivalent. Conceptually, aforeachis more appropriate, as awhileloop has connotations of looping while a static condition holds, whereasforeachloops over elements of a collection. Read “Differences between a while loop and a for loop in PHP?” for part of the story.Be sure to read the php.net reference on PDO