orignal php code
$sql = "SELECT * FROM products WHERE id IN(";
foreach($_SESSION['cart'] as $id => $value){
$sql .=$id. ",";
}
$sql=substr($sql,0,-1) . ") ORDER BY id ASC";
$query = mysql_query($sql);
$totalprice=0;
$totalqunty=0;
if(!empty($query)){
while($row = mysql_fetch_array($query)){
$quantity=$_SESSION['cart'][$row['id']]['quantity'];
$subtotal= $_SESSION['cart'][$row['id']]
['quantity']*$row['productPrice'];
$totalprice += $subtotal;
$_SESSION['qnty']=$totalqunty+=$quantity;
我试过这个
$sql = $conn->prepare("SELECT * FROM products WHERE id IN(");
foreach($_SESSION['cart'] as $id => $value){
$sql .= $id . ","; }
$sql.=substr($sql,0,-1) . ") ORDER BY id ASC";
$query = $conn->prepare($sql);
$query->execute();
$totalprice=0;
$totalqunty=0;
if(!empty($query)){
while($row = $query->fetch(PDO::FETCH_ASSOC) ){
$quantity=$_SESSION['cart'][$row['id']]['quantity'];
$subtotal= $_SESSION['cart'][$row['id']]
['quantity']*$row['productPrice'];
$totalprice += $subtotal;
$_SESSION['qnty']=$totalqunty+=$quantity;
但这不起作用,这是购物车的部分代码。所以请任何人告诉我如何在pdo中更改此代码以及我在pdo中编写的代码有什么问题。
答案 0 :(得分:-1)
您必须添加要执行的参数
$query->execute(array_values($_SESSION['cart']));
但是你不应该直接使用superglobals。您应该始终过滤这些值,并注意变量不是安全威胁。
答案 1 :(得分:-1)
For $conn->prepare you need to pass string as parameter. Pleas check the syntax of $sql string you are passing to conn->prepare.
I think it should be like :
'$sql = "SELECT * FROM products WHERE id IN(";
foreach($_SESSION['cart'] as $id => $value){
$sql .= $id . ","; }
$sql.=substr($sql,0,-1) . ") ORDER BY id ASC";
$query = $conn->prepare($sql);
$query->execute();
$totalprice=0;
$totalqunty=0;
if(!empty($query)){
while($row = $query->fetch(PDO::FETCH_ASSOC) ){
$quantity=$_SESSION['cart'][$row['id']]['quantity'];
$subtotal= $_SESSION['cart'][$row['id']]
['quantity']*$row['productPrice'];
$totalprice += $subtotal;
$_SESSION['qnty']=$totalqunty+=$quantity;`