I'm building a small shopping cart into a website, the cart is stored in a database and works fine except once the visitor places the order if they click back in the browser it lets them add more items to the existing order.

I have the following code run every time something is added to the shopping cart so is there is no CartID set then a new record is inserted into the database and its insert id becomes the session's CartID so any futher products added to the cart are then added to that order.

session_start();

If(!isset($_SESSION['CartID'])) {
     session_register("CartID"); 

 $query = mysql_query("INSERT INTO tblorders (fldIPAddress) VALUES ('" . $_SERVER['REMOTE_ADDR'] . "')") or die(mysql_error());

$_SESSION['CartID'] = mysql_insert_id();


}

Then once the order is finally completed I have tried all kinds of things to make sure that the CartID is destroyed but whenever the visitor clicks back in the browser and adds something else to the cart it still seems to remember the original CartID rather than creating a new one.

I now have this code on the final order confirmation page:

$_SESSION['CartID'] = '';
session_unregister("CartID"); 
session_destroy();

So I'd expect if the visitor clicks back and adds something new to the cart that the first block of code should insert a new record (so creating a new cart) but it seems to just add to the existing one even though the order is complete.

Am I doing something stupid or is it just that the session variables persist when the visitor clicks back so even if I destroy the session it's still there when back is clicked?

    Try unset ($SESSION) unset($SESSION['CartID']).

    I only create an "order" when a payment is received. When the order is created the cart is destroyed. For me that means deleting rows from a cart table in the database. That way, even if somehow their cart id persisted in the session, their cart would still be empty.

      Thanks,

      I tried that but it still seems to persist when I click back and added another item the cart still contained the previous items.

      I think doing it the way you suggested makes more sense too - at the moment anything added to a cart is actually added to an order and when the order is completed it is flagged as being an order and any carts that remain there which haven't become orders after 24 hours are deleted but your way of using a cart table instead would make it more robust so I think I'll try that. 🙂

        Write a Reply...