1
votes

this is a question about the logic of an e-commerce cart built in php:

i have an item in the cart saved with a session in php, this session is named by a composed string where the unique key is given by the product_id:

$this->session->data['quote_total_'.$product_id];

the problem is when i add the same product in the cart but with diefferent price - the price is generated automatically by the system at the change of misures, options, and quantity - indeed the first value of the cart session that is the value of the first product price is overwritten by the new one. which is the best method to avoid this overwrite for you?

i was thinking about a unique value to append at the name of the session but i don't understand which ones...

4

4 Answers

0
votes

How about making this variable an array instead of a primitive datatype?

0
votes

Instead of using the product ID as a key, just let the key be created automatically which will be numerical and incremented with each product

// add a product - new product will always be added
$this->session->data[] = array(
    'product_id' => 123,
    'qty' => 1,
    'name' => 'Product Name',
    'price' => 10
);


// you can iterate over the products like
foreach($this->session->data as $product)
{
    print_r($product);
}
0
votes

Append price with product id in session variable to uniquely identify each product with different prices.And also use array to store multiple products.

-2
votes

Create multidimensional array such as

$data = array([0]=>array(
    'product_id' => 123,
    'qty' => 1,
    'name' => 'Product Name',
    'price' => 10),
    [1]=>array(
    'product_id' => 123,
    'qty' => 2,
    'name' => 'Product Name',
    'price' => 20)
);