Shopping Cart Problems - adding double items to the cart?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JTMarlin8
Forum Newbie
Posts: 4
Joined: Mon Apr 13, 2009 1:43 pm

Shopping Cart Problems - adding double items to the cart?

Post by JTMarlin8 »

Hello Folks,

First post here. I'm writing some shopping cart software based on the book, "PHP and MySQL Web Development, Fourth Edition" by Luke Welling and Laura Thomson. It's pretty decent.

Anyway, here's the problem. Sometimes (not always), my "add-to-cart" link for any given item will add two items to cart instead of one. This only happens about 10% of the time, and most of the time in a new session when the cart session variable has not yet been created. The user could very easily change the qty back to 1 and click "update", but I don't want to give off the impression that we're trying to trick him.

It appears that this is a server side problem (I use Godaddy shared hosting). My add-to-cart link uses the GET variable "new", e.g.

Code: Select all

<a href="show_cart.php?new=12345">Add Item 12345 to Cart</a>  


If there is a slight hangup in the internet connection, for some reason the show_cart.php file will load twice and add two items. I have verified this using echo statements, where it actually first creates the cart, adds one item, then reloads, checks to see cart existence, and then increments the number of that particular item in the cart. Any suggestions for solutions would be very much appreciated. Thanks!

Code: Select all

 
// This is the snippet in show_cart.php that is the culprit
if($new) {
    //new item selected
    if(!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
        $_SESSION['items'] = 0;
        $_SESSION['total_price'] ='0.00';
    }
    
    if(isset($_SESSION['cart'][$new])) {
        $_SESSION['cart'][$new]++;
    } 
    else {
        $_SESSION['cart'][$new] = 1;
    }
    
    $_SESSION['total_price'] = calculate_price($_SESSION['cart']);
    $_SESSION['items'] = calculate_items($_SESSION['cart']);
}
 
JTMarlin8
Forum Newbie
Posts: 4
Joined: Mon Apr 13, 2009 1:43 pm

Re: Shopping Cart Problems - adding double items to the cart?

Post by JTMarlin8 »

So I temporarily changed the code such that if the item is already in the cart, it doesn't do anything to the quantity. That way you can't accidentally add two to the cart. On the otherhand, the only way to increase the quantity is to manually type it in.
Post Reply