James Reeves
James Reeves

Reputation: 97

Shopping Cart - Store in sessions?

I'm developing a shopping cart for a website, and was wondering what way should I store the product id after the user has clicked on the "Add to cart".

Should I store them in a session -- Such as

$_SESSION['cart'][$productid]++;

Would this put strain on the server under load? Or is this the best way of doing it?

Or should I create a temp database table, store the information in there, and remove after order has been processed?

Upvotes: 2

Views: 2918

Answers (2)

Nikolaj Zander
Nikolaj Zander

Reputation: 1270

You should definitely use a database table to store the items. Logged-in users will appreciate that they didn't have to grab all items again, if they come back after some time!

You can keep the information of the cart in the session, to get the information you need, but you should set new information in the session and in the database! And then before checkout you should cross-check your information.

Another advantage is that you can keep track of what is going on in your shop! You wont have any information if no one buys your items and you store the carts in a session.

Upvotes: 1

Fluffeh
Fluffeh

Reputation: 33502

I would store them in a database for sure, but not create a temp table each time. I would suggest you keep a table that has all the unfinished orders along with an identifier for the user.

This will last longer than a session, all it to be retained after a user has logged off and available after that user logs back in again. When then user is logged in, keep their identifier in the session.

Edit: While connecting to a database does consume resources, that is what database servers are made for. A connection to a small table uses next to nothing - I mean, you are probably executing a good number of queries just displaying your shopping cart. If you get to the point where your website can't handle the extra stress due to saving an odd row in a small table, you will be getting enough money from the sales to buy a bigger server :)

Upvotes: 3

Related Questions