我在PHP中创建了一个购物车项目但是在更新购物车项目数量的情况下,它没有按预期工作。最后添加的项目数量只能更新。我显示项目和更新的代码在这里:
<HTML>
<BODY>
<?php
session_start();
include 'connect.php';
if(isset($_POST['update'])) {
$p=$_POST['pname'];
$q=$_POST['quantity'];
$querym =mysql_query("SELECT * FROM product WHERE product_name='$p'");
while ($productByCode = mysql_fetch_array($querym)) {
$itemArray = array($productByCode["product_name"]=>array('name'=>$productByCode["product_name"],'p_id'=>$productByCode["p_id"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["amount"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode["product_name"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode["product_name"] == $k)
$_SESSION["cart_item"][$k]["quantity"] =$q;
}
}
else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
}
}
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<form method="POST">
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th><strong>Total</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
$total =($item["price"]*$item["quantity"]);
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><input type="text" name="quantity" id="<?php echo $item["p_id"];?>" class="quant" value="<?php echo $item["quantity"]; ?>" style="width:35;"><br>
<input type="hidden" name="pname" value="<?php echo $item["name"]; ?>">
<input type="hidden" name="p_id" value="<?php echo $item["p_id"]; ?>">
<p><input type="submit" value="save" name="update"></p>
<td align=right><?php echo "$".$item["price"]; ?></td>
<td><?php echo "$".$total; ?></td>
<td><a href="checkout.php?act=remove&p_name=<?php echo $item["name"]; ?>" class="btnRemoveAction">Remove Item</a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
$_SESSION['tot']=$item_total ;
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong><?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>
<?php
}
?>
</BODY>
</HTML>
提前致谢。
答案 0 :(得分:0)
您的$_SESSION["cart_item"][$k]["quantity"]
是否未更新?
一个建议。您应该真正考虑阻止SQL注入,https://en.wikipedia.org/wiki/SQL_injection。