2017-03-17 67 views
0
if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){ 
     $productID = $_REQUEST['id']; 
     // get product details 
     $query = $db->query("SELECT * FROM products WHERE id = ".$productID); 
     $row = $query->fetch_assoc(); 
     $itemData = array(
      'id' => $row['id'], 
      'name' => $row['name'], 
      'price' => $row['price'], 
      'qty' => 1 
     ); 

     $insertItem = $cart->insert($itemData); 
     $redirectLoc = $insertItem?'viewCart.php':'index.php'; 
     header("Location: ".$redirectLoc); 
    } 

我試圖將此代碼轉換爲PDO stmt。請幫助我,我是新來的。如何將mysqli代碼轉換爲PDO stmt?

+0

'$ db'是'pdo'連接還是'mysqli'?到目前爲止你做了什麼? 'prepare(「SELECT * FROM products WHERE id =?」'''execute(array($ productID))' – chris85

+1

您可能想向我們展示您的數據庫類,以便我們可以看到它在做什麼 – icecub

回答

0

您需要使用您擁有的任何數據庫開發和pdo連接。檢查連接檢查並連接。

確保您已安裝PDO庫,請檢查您的PHP信息。

try 
    {     
     $conn =new PDO("sqlsrv:Server=$this->hostName;Database=$this->dbName", "$this->userName", "$this->password"); 
     $productID = $_REQUEST['id']; 
     $sql = "SELECT * FROM products WHERE id=?"; 
     $stmt->bindParam(1, $productID); 
     $stmt = $conn->prepare($sql); 
     $this->result = $stmt->execute(); 

        if (!$this->result) 
        { 
         while($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
         { 
          $itemData = array(
          'id' => $row['id'], 
          'name' => $row['name'], 
          'price' => $row['price'], 
          'qty' => 1 
          ); 
         } 
        } 
    $insertItem = $cart->insert($itemData); 
    $redirectLoc = $insertItem?'viewCart.php':'index.php'; 
    header("Location: ".$redirectLoc);       
    } 
    catch(Exception e) 
    { 
    echo $e->getMessage(); 
        exit(); 
    }