Jump to content

Issues with an adapted shopping cart


mac007

Recommended Posts

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>
 
Edited by mac007
Link to comment
Share on other sites

How about you use code that isn't complete garbage? I have no idea where you got this stuff from, but it's unfixable, and I don't think anybody is masochistic enough to even try.

 

If you're unable or unwilling to write your own code, use a proper implementation from people who know what they're doing. There are shopping applications all over the place.

Link to comment
Share on other sites

I think one of the misunderstandings is in this line:

if(in_array($productByCode[0]["ProductID"],$_SESSION["cart_item"])) {

You are looking for a scalar, the ProductID within an array of items, of which each are an array having a key of ProductID. This suggests to me you are one dimension too far away to use in_array().

 

But you are within reach of using array_key_exists().

 

Experiment with using:

if(array_key_exists($productByCode[0]["ProductID"],$_SESSION["cart_item"])) {

A concern is when you say, "it doesnt add the quantity to the same product, it simply adds it as another item in the cart". Not finding that same item in $_SESSION['cart_item'], then that should be this statement:

$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);

The array_merge should find that the $itemArray has the same key as an existing element in $_SESSION['cart_item'] and actually replace that existing element, not add another to it.

 

Judicious use of var_dump() should reveal why this isn't happening.

Link to comment
Share on other sites

Thank you much bsmither for taking the time to reply. I will try that! I think lots of us here are not full-fledged php experts as Guru [Jacques1] would like us all to be, else we (I) wouldnt be here. This is a great forum and place to learn, and figure out stuff as we try out our skills. At any rate, I very much appreciate your feedback without having to resort to rather nasty, condescending attitude in the process...

 

Thank you! :)

Edited by cyberRobot
added Jacques1
Link to comment
Share on other sites

if you simplify the cart so that it uses the item_id as the array index and stores the quantity as the array value, all the code will be greatly simplified.
 
when you add something to the cart, you would need to submit the item_id and the quantity. both these values should be submitted as post data.
 
after you validate both submitted values, this is all the logic you need to either initially insert the item into the cart with the submitted quantity or to add an additional quantity to an existing item - 

$item_id = (int)$_POST['item_id'];
// if the item is not in the cart, add it with quantity 0 (the next step will add to the quantity)
if(!isset($_SESSION['cart'][$item_id]))
{
    $_SESSION['cart'][$item_id] = 0; // add the item id to the cart with quantity 0
}
// add the submitted quantity to whatever is in the cart for this item
$_SESSION['cart'][$item_id] += (int)$_POST['quantity'];
Edited by mac_gyver
Link to comment
Share on other sites

At any rate, I very much appreciate your feedback without having to resort to rather nasty, condescending attitude in the process...

 

In other words, you rather want us to tell you a comfortable lie than the nasty truth? That's not exactly the best attitude for a programmer, not even for a hobbyist.

 

The code you've found is riddled with security vulnerabilities, bad design decisions and hopelessly outdated techniques. If it were at least your code, I'd happily give you feedback. But you've copied and pasted it from some random website, and now you're asking others to fix it for you. That's getting you nowhere. You won't learn anything, everybody will spend a lot of time on useless bugfixes, and you'll still end up with bad code.

 

If you want to learn, either write your own code (crazy, right?) or take it from good sources (like a properly managed GitHub project). You cannot learn from websites where the people know less about PHP than you do.

 

For the write-for-scratch case, see mac_gyver's concept.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.