This is my php script for adding item to shopping cart:
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
switch($_GET['action']) {
case 'add':
$productByCode = $db_handle->runQuery("SELECT item, brand, price, catalog FROM products WHERE catalog='".$_GET['catalog']."'");
$itemArray = array($productByCode[0][‘catalog']=>array(
'item'=>$productByCode[0]['item'],
'brand'=>$productByCode[0]['brand'],
'price'=>$productByCode[0]['price'],
'catalog'=>$productByCode[0]['catalog']));
if(!empty($_SESSION['cart_item'])) {
if(!in_array($productByCode[0]['catalog'],($_SESSION['cart_item']))) {
$_SESSION['cart_item'] += $itemArray;
}
}
else {
$_SESSION['cart_item'] = $itemArray;
}
I want to limit the max number of cart item to 20, that means when the cart items has reach 20, even if the user click the add button with new item not found in the $_session, the new item will not be added anymore. Is there any way to do this? Pls help. Thanks in advance.
</div>
You have a couple of issues. in_array won't work the way you have it because it compared the array value not the key. So use array_keys to test for that. You could also use isset($_SESSION['cart_item'][$productByCode[0]['catalog'])
instead of in_array(array_keys(...)) to get the same effect.
I updated the add code to use array_merge so it is clear what is happening with the new cart items.
Also you should parameterize your sql query to avoid SQL injection issues (I didn't correct this in your code)
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
switch($_GET['action']) {
case 'add':
$productByCode = $db_handle->runQuery("SELECT item, brand, price, catalog FROM products WHERE catalog='".$_GET['catalog']."'");
$itemArray = array($productByCode[0][‘catalog']=>array(
'item'=>$productByCode[0]['item'],
'brand'=>$productByCode[0]['brand'],
'price'=>$productByCode[0]['price'],
'catalog'=>$productByCode[0]['catalog']));
if(!empty($_SESSION['cart_item'])) {
if(count($_SESSION['cart_item']) < 20 && !in_array($productByCode[0]['catalog'],array_keys($_SESSION['cart_item']))) {
$_SESSION['cart_item'] = array_merge($_SESSION['cart_item'], $itemArray);
}
}
else {
$_SESSION['cart_item'] = $itemArray;
}
</div>