更新产品购物车会话

update product cart session

在网上的一些帮助下,我制作了一个购物车。但是,有一个问题: 当我将产品 A 放入购物车时,一切正常。但是当我再次将产品 A 放入购物车时,显示:2x 产品。它显示:1x 产品 A,1x 产品 A。 我试图自己解决这个问题,我还查看了不同的购物车如何解决这个问题。我找到了这个脚本并尝试自己编辑,但没有成功。我尝试了 echo 来确定 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>

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

试试这个:

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

希望对您有所帮助。

PS。如果您在问题中正确缩进,我们最高兴 :)!