更新产品推车会话

时间:2015-05-11 11:15:54

标签: php session cart shopping

借助互联网的一些帮助,我能够制作购物车。但是,有一个问题: 当我将产品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>

1 个答案:

答案 0 :(得分:0)

使用in_array,您正在搜索值,并且需要搜索数组的索引

试试这个:

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

我希望它有所帮助。

PS。如果你在问题中正确缩进,我们最开心:)!

相关问题