13

I am starting to develop a multi store shopping cart in php where every user will have a shopping cart under different stores. I would like to know what is the better way to save the shopping cart details like products name, id, price etc, when a user clicks on "Add to Cart". I think we can save it in two ways : a) Session b) Db Table.

Which is the better method to save all these information ? I want to make it as secure as it can be.

Please suggest.

Thanks

Zack
  • 451
  • 2
  • 4
  • 14

3 Answers3

10

You must know the criticality of the data. If you think that the data in your shopping cart is not critical and not needed for multiple sessions that you can just do it with sessions and save some writes to the DB.

Even if you do need a DB you can save some writes and use client side for temp storage and finally move it to your DB with some kind of a syncing mechanism.

But if your data is highly critical and it is mandatory that it persists in multiple sessions then DB would be an ideal choice as it would give you more power over the access to the data and also it will ease the implementation.

swordfish
  • 4,569
  • 5
  • 29
  • 57
  • In case of using a session for visitors shoppingcart, you want as less as possible stored in it. 1 because session data gets passed to the next page ( increase of loadtime), 2 because critical data such as price should not be 'cached' in a session since sessions might exists for a longer period of time. (there are cases where you want to 'cache' it though, but you get the idea right?:) – Frankey Nov 09 '14 at 09:40
  • @Frankey PHP session variables are not sent to the client. The Session ID cookie is used to indicate to the server what session it will associated `$_SESSION` with. – Nick Bedford Feb 05 '15 at 01:09
9

Session or DB is not exclusive choice - session can be stored in database as well. In some way you have to retrieve the cart for the user. In all cases you will have session for this. The question is if the cart should be persisted between sessions (for registered users). In that case you should not couple cart with the session. Things gets complicated if you want to save the cart for registered users, allow unregistered to have cart as well, and merge the session cart and the saved cart in case user logins.

So to answer your question, you should just clear your requirements. What means 'shopping cart under different stores'? Will be cart saved between logins (for example user comes back 1 week later)?

As for the security, it's usually preferred to save session in the database, as you can have additional protection who have access to the data, especially on a shared hosting.

Maxim Krizhanovsky
  • 24,757
  • 5
  • 49
  • 85
0

With a DataBase implementation you have granular control and better persistence.

Use Session to know the loginned user between pages, but DataBase to store critical data.

corretge
  • 1,642
  • 10
  • 21