Add products to the cart of the same id with different variants

Hi all, I’m a new user. I have a shopping cart php script that works fine.
I made changes by adding different variants to each product.
Now when I add the product by selecting the variants it works perfectly.
However, if I try to add the same product but with different variants, the previous product is overwritten and only the newly added product remains.
I would like both products to stay.
I apologize if my english is not correct but I use google translate.

Here is the code that opens the cart sessions:

session_start();

//check for additions
if (isset($_POST['aggiunta'])){
// original string 
$OriginalString = $_POST['aggiunta']; 
$matches = implode(',', $OriginalString);
$sql = "SELECT * FROM aggiunte WHERE aggiunta_id IN ($matches)";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$descrizione_aggiunta[]=$row["descrizione_aggiunta"];
$valore_aggiunta[]=$row["valore_aggiunta"];
$aggiunta_id[]=$row["aggiunta_id"];
$tipo_aggiunta[]=$row["tipo_aggiunta"];
$somma +=$row["valore_aggiunta"];
$_SESSION['aggiunta_id'][]=$aggiunta_id;
$new_product['valore_aggiunta']=$valore_aggiunta;
$new_product['descrizione_aggiunta']=$descrizione_aggiunta;
$new_product['aggiunta_id']=$aggiunta_id;
}
}
}


if(isset($_POST["remove_code"]) OR isset($_POST["product_qty"])  && isset($_SESSION['coupon']))
{
    unset($_SESSION['coupon']);
}
//add product to session or create a new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0  )
{
unset($_SESSION['coupon']);
foreach($_POST as $key => $value){ //aggiungi tutte le variabili post all'array new_product
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
unset($new_product['type']);
unset($new_product['return_url']); 
//we need to get product name and price from database.
$statement = $conn->prepare("SELECT coupon_name,prezzo_reale,acconto,coupon_shop,multi_deal,gratis FROM coupons_coupons WHERE coupon_id=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($coupon_name,$prezzo_reale,$acconto,$coupon_shop,$multi_deal,$gratis);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["coupon_name"] = $coupon_name; 
$new_product["multideal"] = $multi_deal; 
$new_product["coupon_shop"] = $coupon_shop;
$prodotto=$_POST['product_code'];
$new_product["product_price"] =  $prezzo_reale+$somma;  
if(isset($_SESSION['shop'])){
}
else
{
$_SESSION['shop'][] = $new_product["coupon_shop"];
}
if(isset($_SESSION["cart_products"])){  //if the session var already exists
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check that the item exists in the products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //delete the old element of the array
}           
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //refresh or create a product session with a new item
} 
}


//update or remove items 
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
	//update item quantity in product session
	if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
		foreach($_POST["product_qty"] as $key => $value){
			if(is_numeric($value)){
				$_SESSION["cart_products"][$key]["product_qty"] = $value;
			}
		}
	}

//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
unset($new_product['multideal']);
unset($_SESSION['descrizione_opzione']);
}	
}
}
//back to return url```

Thanks to anyone who wants to help me I'm still learning.

Well it looks like items might be added to the cart based on their product code. If you add something to the product code to also describe the variant, they should be seen as two different products rather than the same product code with two different variants.

I hope you get what I mean. For example, assume a product has a code of “LRG-SHIRT”. If you have two color variants, both will be LRG-SHIRT. So make one LRG-SHIRT-GREEN and the other LRG-SHIRT-RED.

1 Like

Thanks for the reply. I thought about it too and I tried to do it but I can’t.
I’m at the first studies with php.
As you suggested I should add the variant id to the product code.
Can you give me an example by modifying my code? Thank you !

Well I don’t speak Italian so I am having trouble understanding all your keys and variables at the beginning. I also don’t see where you actually set $new_product['product_code']. But wherever you do that, you just need to append on the variant value…

$new_product['product_code'] .= "_{$product_variant}";

You need to do this AFTER you lookup the original product_code in the database (where you add it to your session). If you do it before, you probably won’t find the product since LRG-SHIRT-GREEN is not in your database as a product code, it is LRG-SHIRT.

Then when it comes to building the order, you are going to have to take this new product code and split off the variant part of it again so that you can lookup the product, use the variant piece to find the correct variant for it and put it on the order.

In other words, when it comes to building the order (after they hit purchase) you take LRG-SHIRT-GREEN and you split off -GREEN, lookup the product LRG-SHIRT and then use -GREEN to know that they selected the variant GREEN (maybe even modify the price… because green shirts cost more)

Hopefully you get it.

I don’t want to make this sound confusing, but if you are just learning PHP (or programming in general), ecommerce scripts and such can be awfully complicated to work with. There is a lot to go into them. If you are really struggling, I suggest maybe you get another experienced programmer (preferably one with ecommerce experience) to help out. Learning to program and trying to juggle business rules and put it together in ecommerce (where mistakes can cost you money) can be a real challenge.

P.S. Before you put this script out there to the public, have someone look over it for security issues. I see you have a security problem called SQL injection that could take place here. :slight_smile:

Thank you very much Martyr you have been very kind and paved the way for me to continue.
I understood everything you wrote and I will try to do it.
I pass the session in the cart with product code + variant and then I will make sure to divide the ids to identify the product in the checkout process.
Subsequently I also provide to protect the code from SQL injection.
I’ll update you as soon as possible. Thanks again for the support!
Regards,
Massimo

Well because you wish to have the possibility multiple items with the same product code you wouldn’t be checking is that product is in the cart and deleting it, SO this whole section would not be used under proposed model allowing for multiple items with the same product code.

if(isset($_SESSION["cart_products"])){  //if the session var already exists
	if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check that the item exists in the products array
	{
		unset($_SESSION["cart_products"][$new_product['product_code']]); //delete the old element of the array
	}           
}

Now under $_SESSION["cart_products"] you would no longer define the key as [$new_product['product_code']]. Instead you would use natural keys, i.e 0, 1, 2 etc. defined as

$_SESSION["cart_products"][] = $new_product;

When building your “cart” form you are looping through your cart you are probably doing something like this (not including any html display etc). Sample only to show KEYS.

if(!empty($_SESSION["cart_products"])){
	foreach($_SESSION["cart_products"] as $key => $product){ 
	   echo '<input type="text" name="product_code['.$key.']" value="'.$product['product_code'].'">'; 
	   echo '<input type="text" name="product_qty['.$key.']" value="'.$product['product_qty'].'">';
	}
}

These $key values are the natural array keys, i.e 0, 1, 2 so all form inputs correspond to the key in the $_SESSION["cart_products"] array.

Each item in your cart COULD have an “Update” And a “Delete” button. They might look something like this.

echo '<input type="submit" name="update_product['.$key.']" value="Update">';
echo '<input type="submit" name="delete_product['.$key.']" value="Delete">';  

This makes it nice as you are actually editing the item in the array instead of rebuilding $_SESSION["cart_products"] looping through the whole form.

You can Identify the button pushed by using array_search() which will return the array KEY if the VALUE searched for is found. Say I push that update_product shown above. The name of the button is update_product and we search for the value Update and set the key to $ekey.

$ekey = array_search("Update", $_POST['update_product']);

This key can be used to get all form input values for this item that might be in the cart. For example:

$_POST['size'][$ekey]
$_POST['color'][$ekey]
$_POST['weight'][$ekey]

You are wishing to update the qty and remember the KEY is the same for $_POST and $_SESSION['cart_products'] so the update would be

$_SESSION['cart_products'][$ekey]['product_qty'] = $_POST['product_qty'][$ekey];

So the total Update code section would be.

if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_product'])):	

	$ekey = array_search("Update", $_POST['update_product']);
		
	if(!empty($_POST['product_qty'][$ekey]) && is_numeric($_POST['product_qty'][$ekey])):		 
		$_SESSION['cart_products'][$ekey]['product_qty'] = $_POST['product_qty'][$ekey];
	endif;
endif;

To remove an item from the cart you get the KEY in the same way as in the Update, changing the search terms and then unset() the array KEY.

if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_product'])):

	$dkey = array_search("Delete", $_POST['delete_product']);	
	unset($_SESSION['cart_products'][$dkey]);	
endif;

All processing code should be above output to the browser so as the page reloads, updated values are displayed.

Hi Drummin, and thanks a lot for your reply.
In reality Martyr2 dictated the road to me and I have already resolved everything with his advice. In fact, now I can add more products of the same id but with different variants and options. The variants and options were already saved in session with an array and therefore the whole process worked correctly.
I only changed the product ID during payment confirmation and everything works perfectly. Right now I’m cleaning and protecting the code from sql injection.
Thanks again for your contribution.
See you soon!
Massimo

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.