2015-05-11 144 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