Limit number of items added to cart based only on ID even though key has ID and concatenated value

A customer has the option of selecting an outlet when they add an item to the cart. Even though a product may be associated with multiple outlets, the product only has 1 ID. If the user was to add the same product to the cart, but choose 3 separate branches, it would just just 1 line in the cart with a quantity of 3. That was not how it should work so I concatenated my ID with the outlet ID so that in the cart 3 separate items would appear even though it was the same product. This works fine but my problem comes in when there is not enough stock.

Let's say there is only 1 item in stock. If I add it to the cart and select a particular outlet, it adds to the cart. If you do this again and select another branch it should not add to the cart because there is only one on hand. It is however letting me add 1 for every different branch selected. It should only let me add 1 no matter how many different outlets I may try to choose.

      
$key = "{$prod_id}.{$outlet_id}";
       if (empty($_SESSION['cart_array'][$key])) {
         $_SESSION['cart_array'][$key] = array(
            'prod_id'    => $prod_id,
            'outlet_id'  => $outlet_id,
            'quantity'   => $quantity,
            'prod_name'  => $data['prod_name'],
            'sale_price' => $data['sale_price'],
            'sp_name'    => $data['sp_name'],
            'outlet_name' => $data['outlet_name']

         );

           $response['success'] = true;
           $response['message'] = 'Product added to cart.';
       }

       elseif($_SESSION['cart_array'][$key]['quantity'] >= $data['numVouchersLeft']) {

           $response['success'] = false;
           $response['message'] = 'Insufficient stock. Cannot add to cart.';

       } else {

             $_SESSION['cart_array'][$key]['quantity'] += $quantity;
             $response['success'] = true;
             $response['message'] = 'Product added to cart.';
       }

Open in new window


This is probably the line that needs to change but not sure exactly how:

elseif($_SESSION['cart_array'][$key]['quantity'] >= $data['numVouchersLeft']) {

Open in new window


I tried something like this but it did not work:

elseif($_SESSION['cart_array'][$key]['prod_id']['quantity'] >= $data['numVouchersLeft']) {

Open in new window

LVL 1
Black SulfurAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Where is the total stock item stored?
Scott FellDeveloper & EE ModeratorCommented:
To me it seems like this would be easier to store the cart in your database instead of a session.  I typically use two tables, one for a sales order header and the other for item details.   The header could hold the session id, date and a place for the buyers name. Then the line item table would include the product id, outlet id, qty and price.    Then when displaying the data, do a group by on the product id so you have one line item per product in the view.

Each time the page loads to show the items, I would query the db for the availability. If availability is by location/outlet, add logic to know there are 3 widgets in location 1 and 0 in location 2.  If they order 2 widgets for outlet 2, your logic should display there is no availability in location 2 but x left in location 1.  

It will be much easier to manage using the database.

At time of actual purchase, do a final look up for availability because you may have multiple people placing the same item in their carts at the same time and you want to give those items to the person that actually goes through with the purchase and not take it out of inventory just by adding to the cart.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Black SulfurAuthor Commented:
@ Julian,

Not sure if you are referring to the total stock of each item? If so, I have a SQL query that counts the number of vouchers available in the database i.e.: ones that haven't been purchased yet. That is sent to the controller i.e.:

$data['numVouchersLeft']

Open in new window


@ Scott, good idea. I might try move over to a database but at that may require a lot of reworking. Definitely something to think about.

Just to expand on my problem, let's say there is only 1 voucher for ice-cream left but that voucher can be redeemed at any ice-cream store in the area.

Before I can click on 'add to cart', I have to select an outlet. Once I select the outlet I can then click add to cart. If I click add to cart then it will show the 1 last voucher in my cart. If I then go back and select another branch, and then add to cart, it should not let me do that because I can't add 2 vouchers to the cart if there is only 1 in stock.

If I choose the same branch twice then it works fine but if I select 2 different branches then it sees it as 2 different products because the $key is different for each branch.
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Julian HansenCommented:
I was referring to the point you made
Let's say there is only 1 item in stock. If I add it to the cart and select a particular outlet, it adds to the cart. If you do this again and select another branch it should not add to the cart because there is only one on hand. It is however letting me add 1 for every different branch selected. It should only let me add 1 no matter how many different outlets I may try to choose.

Your add process should always check all the parameters needed before adding the item to the cart. This would include checking what is already in the cart and comparing that to what is in the DB.
Black SulfurAuthor Commented:
Thanks Julian, that is what I am struggling with. Trying to check only what product id is already in the cart, not the key of product id + outlet id.

On this line:

elseif($_SESSION['cart_array'][$key]['quantity'] >= $data['numVouchersLeft']) {

Open in new window


I am checking what key is in the cart already and then checking it against how many are available in the database. So the key would end up being something like 3.9 (product id of 3, outlet id of 9) but I only want to check against product ID as the stock levels based on outlets are irrelevant.

So, I tried this:

  elseif($_SESSION['cart_array'][$key]['prod_id']['quantity'] >= $data['numVouchersLeft']) {

Open in new window


But realized this won't work because I am still looking inside [$key] which has the two id's concatenated. I somehow need to just check against the product ID only. I considered perhaps creating a second key but that just seems like it's going to get unnecessarily messy and confusing.
Black SulfurAuthor Commented:
Just as a test, I did this:

 $key = "{$prod_id}.{$outlet_id}";
$keytwo = $prod_id;
			
			
		   if (empty($_SESSION['cart_array'][$key])) {
			 $_SESSION['cart_array'][$key] = array(
				'prod_id' 	 => $prod_id,
				'outlet_id'  => $outlet_id,
				'quantity' 	 => $quantity,
				'prod_name'  => $data['prod_name'],
				'sale_price' => $data['sale_price'],
				'sp_name' 	 => $data['sp_name'],
				'outlet_name' => $data['outlet_name']
				
			 );
			   
			 $_SESSION['cart_array_products'][$keytwo] = array(
			 	 'prod_id' => $prod_id,
				 'quantity2' => $quantity
			 );
			   

			   
			   $response['success'] = true;
			   $response['message'] = 'Product added to cart.';
		   }

		   elseif($_SESSION['cart_array'][$key]['quantity'] >= $data['numVouchersLeft'] || $_SESSION['cart_array_products'][$keytwo]['quantity2'] >= $data['numVouchersLeft']) {
			   
			   $response['success'] = false;
			   $response['message'] = 'Insufficient stock. Cannot add to cart.';
			
		   } else {
			   
			     $_SESSION['cart_array'][$key]['quantity'] += $quantity;
			     $_SESSION['cart_array_products'][$keytwo]['quantity2'] += $quantity;
			   	 $response['success'] = true;
				 $response['message'] = 'Product added to cart.';
		   }

Open in new window


But for some reason if I add the same product from 2 different outlets, the quantity goes back to 1 for the $_SESSION['cart_array_products]
Black SulfurAuthor Commented:
I have managed to solve the issue as per below, but if anyone has a better or more elegant solution then please let me know as I don't think this is the best way.

if(empty($_SESSION['cart_array'][$key])) {
						 $_SESSION['cart_array'][$key] = array(
							'prod_id' 	  => $prod_id,
							'outlet_id'   => $outlet_id,
							'quantity' 	  => $quantity,
							'prod_name'   => $data['prod_name'],
							'sale_price'  => $data['sale_price'],
							'sp_name' 	  => $data['sp_name'],
							'outlet_name' => $data['outlet_name']

						 );
						
					} elseif($_SESSION['cart_array_products'][$keytwo]['quantity'] < $data['numVouchersLeft']) {
						
						$_SESSION['cart_array'][$key]['quantity'] += $quantity;
						$response['success'] = true;
						$response['message'] = 'Product added to cart.';	  
						
					} else {
						
						$response['success'] = false;
						$response['message'] = 'Not enough stock to add item to cart.';
					}
		
					if(empty($_SESSION['cart_array_products'][$keytwo])) {
						$_SESSION['cart_array_products'][$keytwo] = array(
							'prod_id'  => $prod_id,
							'quantity' => $quantity
					);
				
						$response['success'] = true;
						$response['message'] = 'Product added to cart.';
				
					} elseif($_SESSION['cart_array_products'][$keytwo]['quantity'] >= $data['numVouchersLeft']) {
						
						$response['success'] = false;
						$response['message'] = 'Not enough stock to add item to cart.';
						
					} else {
						
						$_SESSION['cart_array_products'][$keytwo]['quantity'] += $quantity;
						$response['success'] = true;
						$response['message'] = 'Product added to cart.';
					}

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.