简体   繁体   中英

How to store shopping cart items by unique ID in $_SESSIONS?

I am developing a Shopping cart application and I am needing help about storing cart items using $_SESSION.

The Concept

When user clicks on Add to Cart, the following information is stored: Product ID eg 5312, Product Name, Product Quantity, Product Rules (eg color : white, size : medium and so on)

The problem

The problem is that when I save the entry in $_SESSION by item ID. I want to assume the following:

  • User adds 1 item of product #11 which color is white
  • User then adds 2 items of product #11 which color is blue

If I save by item ID, the info will be overridden always, I want to make each call / each add to cart unique because I am assuming he may add different sizes, different colors of the same product.

How can I come over such a problem?

Any ideas or inputs are greatly appreciated.

You can do a multidimensional array with your SESSION variable.

$_SESSION['cart']=array(
    $product_id=>array($product_count,$product_options),
    $product_id=>array($product_count,$product_options),
);

Or if the $product_id isn't unique:

$_SESSION['cart']=array(
    array($product_id,$product_count,$product_options),
    array($product_id,$product_count,$product_options),
);

With something like this, you can have a unique product id as the array key, then store the count, options, and other info you need.

Another option would be to create a table for your shopping cart, and then have the session store the cart ID. Then you would simply check the mysql table for your cart info.

您可以使用产品ID作为密钥存储阵列。

Instead of storing a product in session store a cart item object. Cart item object would have a reference to the product (product ID) along with any attributes for that item (color, quantity, different price if necessary etc.). Assign a random ID to each cart item and you never run into a problem of overriding.

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