【发布时间】:2017-11-30 15:36:33
【问题描述】:
一直在修改我的添加到购物车功能的代码,如果产品已经存在于购物车中,我在不更新数量方面遇到了一些困难。 它只会为添加到购物车的第一个产品正确更新。
我的更新添加到购物车代码是:
// -------------------------
// Adding item
// -------------------------
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_id='" . $_GET["product_id"] . "'");
$itemArray = array($productByCode[0]["product_id"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_description'=>$productByCode[0]["product_description"],
'product_id'=>$productByCode[0]["product_id"], 'quantity'=>$_POST["quantity"], 'product_price'=>$productByCode[0]["product_price"],'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["product_id"], array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["product_id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
我在代码中遗漏了什么吗?
谢谢。 斯坦。
编辑: 更新的代码不起作用:
// -------------------------
// Adding item
// -------------------------
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_id='" . $_GET["product_id"] . "'");
$itemArray = array($productByCode[0]["product_id"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_description'=>$productByCode[0]["product_description"],
'product_id'=>$productByCode[0]["product_id"], 'quantity'=>$_POST["quantity"], 'product_price'=>$productByCode[0]["product_price"],'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["product_id"], array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["product_id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
**foreach($_SESSION["cart_item"] as $k =>&$v){
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}**
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
【问题讨论】:
-
您的代码容易受到SQL injection 攻击。您应该通过mysqli 或PDO 驱动程序使用带有绑定参数的预处理语句。 This post 有一些很好的例子。
-
既然您现在已经发布了您的实时 URL 和有关您的数据库结构的信息,您将希望立即将此离线。网络上的任何人现在都可以清除您的数据库。
-
链接到演示并不是在这里获得帮助的最佳方法。请查看SO's how to create a Minimal, Verifiable example。请包含您的表单的 html。
标签: php session shopping-cart