PHP购物车显示问题

时间:2013-03-12 14:52:50

标签: php shopping-cart

为我的网站创建购物车时,我为各个产品添加和删除功能。当我添加产品时,它会将其添加到表中的新行,而不是当前行。

以下是添加和删除产品的代码:

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);
}

1 个答案:

答案 0 :(得分:0)

也许剪掉这个

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
}

下至三行并让我知道它是否仍无效。

if (!isset($_SESSION['cart'])) $_SESSION['cart']=array();
if (!isset($_SESSION['cart'][$product_name])) $_SESSION['cart'][$product_name]=$product_qty;
else $_SESSION['cart'][$product_name]+=$product_qty;