Hi all, I adapted this simple shopping cart into my site, but it's got 2 issues...
1) if a product is already in the cart, and I add another quantity to it, it doesnt add the quantity to the same product, it simply adds it as another item in the cart
and...
2) if I click on "Remove item" from the cart, it only removes the item if there's only one item in it, if there are many items, it then doesnt do anything.
Appreciate any help!!
Tnanks!
Here's the code:
/* THIS FIRST SECTION IS THE MAIN CART SCRIPT */
require_once("Connections/dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM works WHERE ProductID='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["ProductID"]=>array('name'=>$productByCode[0]["Description"], 'code'=>$productByCode[0]["ProductID"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["Price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["ProductID"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["ProductID"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
/* AND THIS SECTION HERE IS THE CART-DISPLAY HTML SECTION*/
<div id="shopping-cart" align="center">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="shopping-cart.php?action=empty">Empty Cart</a><br />
<br />
</div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
}
?>
<table width="600" border="1" align="center" cellpadding="5" cellspacing="0">
<tr>
<td><strong>Name</strong></td>
<td><strong>Code</strong></td>
<td><strong>Quantity</strong></td>
<td><strong>Price</strong></td>
<td><strong>Action</strong></td>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["code"]; ?></td>
<td><?php echo $item["quantity"]; ?></td>
<td align=right><?php echo "$".$item["price"]; ?></td>
<td><a href="shopping-cart.php?action=remove&code=<?php echo $item["code"]; ?>" class="btnRemoveAction">Remove Item</a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</table>
</div>