简体   繁体   中英

shopping cart in php with session & database

I had developed a shopping cart in PHP using sessions and a database.

If the user is not logged in (a guest), the cart items are stored in the $_SESSION["cart"] variable.

If the user is logged in, all of the cart items from the $_SESSION["cart"] (if any) are copied to database and any previous cart items from database (if any) are also copied back to $_SESSION["cart"] . Here I'll keep the copies both in the session and the database.

As long as user is logged in i don't have the problem with the cart items.

Since I am using session for guests, I'll certainly lose the cart details as soon as browser is closed.

How can I overcome this scenario?

I am trying to store guest cart details in a database, with a unique cookie value. Suggestions please? cart Table Details :

cart_id*
user_id
product_id
product_option_id
product_count
total_amount
time_stamp

user_id+product_id+product_option_id is Unique

Here is the program flow that I would make. It's vague so you can implement it however you want to.

  1. Create a random session ID, perhaps even as simple as with Math.random() .
  2. Check in DB of carts to see if that ID is taken. If so, go back to step 1.
  3. Create an entry in carts DB with that session ID, with the cart ID.
  4. Create a cookie $_COOKIE["carts"] with that session ID.
  5. Every time the user updates the cart (ie, adds or removes an item), check the cookie for the session ID and change the info from the DB.
  6. When cart is submitted, retrieve session ID from cookie and retrieve DB info with that session ID, and then do your PHP magic to buy (empty the cart) with that data from the DB.
  7. Remove the cookie and delete the entry from the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM