2015-05-11 139 views
0

藉助互聯網的幫助,我可以製作購物車。但是,有一個問題: 當我將產品A放入購物車時,一切正常。但是,當我再次將產品A放入購物車時,顯示:2x產品。它顯示:1x產品A,1x產品A. 我試圖自己解決這個問題,我也查找了不同的購物車如何解決這個問題。我發現這個腳本,並嘗試編輯自己,但沒有運氣。我試着回聲確定IF函數是否工作,但不是。 此聲明:if(in_array($productByCode[0]["productid"],$_SESSION["cart_item"])),不起作用。 這是我下面的代碼:更新產品購物車會話

/*add product */ 
if(!empty($_POST["quantity"])) { 
    $con = new DBController(); 
    $productByCode = $con->runQuery ("SELECT * FROM opdracht14_product WHERE productid='" . $_GET["productid"] . "'"); 
    $itemArray = array($productByCode[0]["productid"]=>array('naam'=>$productByCode[0]["naam"], 'productid'=>$productByCode[0]["productid"], 'quantity'=>$_POST["quantity"], 'prijs'=>$productByCode[0]["prijs"])); 

    if(!empty($_SESSION["cart_item"])) { 
     if(in_array($productByCode[0]["productid"],$_SESSION["cart_item"])) { 
      foreach($_SESSION["cart_item"] as $k => $v) { 
       if($productByCode[0]["productid"] == $k) 
        $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"]; 
        echo "hoia"; 
      } 
     } else { 
      $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); 
      echo "hoib"; 
     } 
    } else { 
     $_SESSION["cart_item"] = $itemArray; 
     echo "hoic"; 
    } 
} 

<?php 
while($row = mysqli_fetch_array($result)) { 
?> 
    <form method="post" action="opdracht14.php?action=add&productid=<?php echo $row["productid"]; ?>"> 
     <h3><?php echo $row['naam'] ?></h3> 
     <br/> 
     <img alt="<?php echo $row['alt'] ?>" src="afbeeldingen/<?php echo $row['link']?>"><br/> 
     Prijs:<br/> 
     <span name="naam"><?php echo $row['prijs'] ?></span><br/> 
     Omschrijving:<br/> 
     <p><?php echo $row['omschrijving'] ?> </p> 
     <br/> 
     <input class="hoeveelheid" type="number" name="quantity" value="1"> 
     <input type="submit" value="bestellen" name="submit"> 
    </form> 
<?php 
    } 
?> 

此代碼是另一頁上,以顯示代碼:

if(isset($_SESSION["cart_item"])){ 
    $item_total = 0; 
?> 
<table cellpadding="10" cellspacing="1"> 
    <tbody> 
     <tr> 
      <th><strong>Name</strong></th> 
      <th><strong>Productcode</strong></th> 
      <th><strong>Quantity</strong></th> 
      <th><strong>Price</strong></th> 
     </tr> 
<?php  
    foreach ($_SESSION["cart_item"] as $item){ 
?> 
     <tr> 
      <td><?php echo $item["productid"]; ?></td> 
      <td><?php echo $item["naam"]; ?></td> 
      <td><?php echo $item["quantity"]; ?></td> 
      <td align=right><?php echo "€ ".$item["prijs"]; ?></td> 
     </tr> 
    <?php 
     $item_total += ($item["prijs"]*$item["quantity"]); 
    } 
} 
    ?> 

    </table> 
</div> 
+0

哦,被編輯縮進!謝謝@Naruto – pabgaran

+0

感謝您編輯我的帖子@Naruto。 – dutchrocks

回答

0

隨着in_array您可以在值搜索,你需要在數組的索引搜索

試試這個:

if(isset($_SESSION["cart_item"][$productByCode[0]["productid"]])) 

我希望它能幫助。

PS。如果你在你的問題中正確縮進,我們是最快樂的:)!

+0

謝謝,它的工作。對於我的下一篇文章,我會正確識別。 – dutchrocks