【问题标题】:How to Increment the quantity using ajax, php sessions?如何使用 ajax、php 会话增加数量?
【发布时间】:2015-10-23 21:05:08
【问题描述】:
session_start();
$quantity=1;
$id=$_POST['id'];

    $productByCode= Yii::app()->db->createCommand("SELECT * FROM products where id='".$id."'")->queryRow();
    $itemArray = array($productByCode["id"]=>array('ItemName'=>$productByCode["ItemName"], 'id'=>$productByCode["id"], 'price'=>$productByCode["price"], 'quantity'=>$quantity));


if(!empty($_SESSION["cart_item"])) {
    if(array_key_exists($productByCode["id"],$_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
        if($productByCode["id"] == $k)
            $_SESSION["cart_item"][$k]["quantity"] += $quantity;
        }
    } 
    else {
        $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
    }
} 
else {
    $_SESSION["cart_item"] = $itemArray;
}


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

<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>        
  <?php
}

我有上面的示例代码,当我们点击添加到购物车产品时显示结果,会话中的 n 个商店

Name    Quantity    Price
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
                 Total: $300

但我想这样显示,当我们点击产品上的添加到购物车按钮时,只会增加数量而不是重复产品。

Name    Quantity    Price
Banana  6           $50.00

                     Total: $300

【问题讨论】:

    标签: javascript php jquery ajax session


    【解决方案1】:

    试试这个,

    <?php  
    $item_quantity = 0;     
        foreach ($_SESSION["cart_item"] as $item){
        $item_name= $item["ItemName"];              
        $item_price= $item["price"];              
        $item_quantity +=$item["quantity"];
        $item_total += ($item["price"]*$item["quantity"]);
        }
    ?>
                <tr>
                <td><strong><?php echo $item_name; ?></strong></td>
                <td><?php echo $item_quantity; ?></td>
                <td align=right><?php echo "$".$item_price; ?></td>
                </tr>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 2018-04-04
      • 2016-12-23
      • 2023-04-04
      相关资源
      最近更新 更多