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