0
为我的网站创建购物车时,我为每个产品添加和删除功能。当我添加产品时,它会将其添加到表中的新行中,而不是当前行。PHP购物车显示问题
下面是用于添加和删除产品代码:
function addproduct($product_id, $product_qty){
$q = "SELECT p_name FROM Product WHERE product_id = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['p_name']; //get the product name from product id because it is better to display name than id in the cart
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
$cart[$product_name] += $product_qty;
}
else { //otherwise, add new product-quantity pair to the array
$cart[$product_name] = $product_qty;
}
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
$cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
$_SESSION['cart'] = $cart; //write the updated array back
}
mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
$q = "SELECT p_name FROM Product WHERE product_id = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['p_name'];
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if product exists, update quantity
$cart[$product_name] -= $product_qty;
if ($cart[$product_name] == 0){ //if the qty 0, delete key
unset($cart[$product_name]);
}
}
else { //exception
echo "<p>Error1</p>";
}
$_SESSION['cart'] = $cart; //write array back to session variable
} else {
echo "<p>Error2</p>";
}
mysqli_free_result($result);
}
我们不需要在该代码中看到deleteproduct。你能举出$ product_name的例子吗?当你通过改变你的ifs你只能做一次时,你也会做两件事情。 – Popnoodles 2013-03-12 14:55:43
你的问题是什么? – tlenss 2013-03-12 14:58:34
我的问题是我如何停止另一行被添加到表中时,我添加一个项目的额外数量? – 2013-03-12 15:05:57