簡體   English   中英

如何使用ajax,php會話增加數量?

[英]How to Increment the quantity using ajax, php sessions?

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
}

我有上面的示例代碼,當我們單擊添加到購物車產品時,它會顯示結果

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

嘗試這個,

<?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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM