2017-04-07 57 views
0

一部開拓創新的PHP代碼我要如何改變這種代碼的MySQL,以PDO

$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; 

,但是這是行不通的,這是一個購物車的部分代碼.so請有人可以告訴我如何在pdo中更改此代碼,以及我在pdo中編寫的代碼有什麼問題。

+2

你準備兩次,你不綁定。你的代碼亂七八糟。你有沒有閱讀PDO手冊? http://php.net/manual/en/book.pdo.php或做了一個教程? https://phpdelusions.net/pdo –

+0

好吧,但我怎麼可以改變這行代碼$ sql =「選擇*從產品在哪裏ID IN(」; foreach($ _ SESSION ['cart'] as $ id => $值){ $ sql。= $ id。「,」;} $ sql。= substr($ sql,0,-1)。「)ORDER BY id ASC」;如果我不準備兩次 – Shubham

+0

@Shubham刪除第一個$ conn->準備 –

回答

-1

您必須添加參數來執行

$query->execute(array_values($_SESSION['cart'])); 

但是你不應該直接使用超全局變量。您應該始終過濾這些值並注意,這些變量不是安全威脅。

-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;`