Preventing customers adding more to cart than in stock
Here is my method for preventing customers adding more to their cart than is available.
I'm posting this for 3 reasons...
1. To help anyone to achieve the same thing
2. To allow anyone with much better coding skills than me to (constructively) criticize the content, to help improve the code, with the ultimate aim of having an accepted solution.
3. To start the creation of unofficial 'how to' documents to round out the functionality of ecart
My eCart is called blu_basket
Here i am dealing with 2 pages...
itemdetail.php, which includes my add to cart form
basket.php, which includes all of the cart details
In basket.php, declare 2 arrays ($itemid and $itemqty) before the basket loop , then use the loop, to populate the arrays with the item ID and quantity,
$itemid = array();
$itemqty = array();
while (!$blu_basket->EOF()) {//existing line
$itemid[] = $blu_basket->DisplayInfo("ID");
$itemqty[] = $blu_basket->DisplayInfo("Quantity");
After the line $blu_basket->MoveFirst();
at the end of the same block of php code, add the following code
$itemid_s = serialize($itemid);
$itemqty_s = serialize($itemqty);
This serializes the arrays so they can be stored as session variables, then store the serialized arrays as session variables
$_SESSION["itemid"] = $itemid_s;
$_SESSION["itemqty"] = $itemqty_s;
In itemdetail.php add the following code before the add to cart form
<?php
if (isset($_SESSION["itemqty"]) && (isset($_SESSION["itemid"]))) {//if we have (or had) something in the basket in this session
// set variables for the items and their quantities in the basket, stored as serialized arrays from basket.php in the session variables below
$itemid_s = $_SESSION["itemid"];
$itemqty_s = $_SESSION["itemqty"];
// unserialize the arrays so they are in the correct format again
$itemid = unserialize($itemid_s);
$itemqty = unserialize($itemqty_s);
$itemidkey = array();//initialise an array, (Required in case item has been added to the basket then removed)
foreach ($itemid as $key => $value) {// loop through the items in the basket
if ($value == $row_rsItemDetail['ItemID']) {// if the current itemid is there **
$itemidkey[$key] = $value;//create a new array for all instances of this itemid, putting the keys where
// they occur in an associative array so they match up with the quantities in the $itemqty array
}
}
$matchqty = array_intersect_key($itemqty,$itemidkey);// where they keys match, we get the quantities for this itemid
$qtyinbasket =(array_sum($matchqty));
//echo $qtyinbasket; //print variable until you are happy all is working
}
else {
$qtyinbasket = 0 ;
}
//** if there is no matching itemid in the basket, then the variable $qtyinbasket will be 0
// use this variable to enable / disable the add to cart button
//job done !!