限制$ _SESSION中的最大购物车数量

时间:2017-07-26 12:48:52

标签: php

这是我用于将商品添加到购物车的PHP脚本:



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;
}




我想将购物车项目的最大数量限制为20,这意味着当购物车商品达到20时,即使用户点击了在$ _session中找不到新商品的添加按钮,新商品也不会再加上。有没有办法做到这一点?请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:1)

你有几个问题。 in_array不会按照你的方式工作,因为它比较了数组值而不是键。所以使用array_keys来测试它。您也可以使用isset($_SESSION['cart_item'][$productByCode[0]['catalog'])代替in_array(array_keys(...))来获得相同的效果。

我更新了添加代码以使用array_merge,因此很清楚新购物车项目会发生什么。

此外,您应该参数化您的SQL查询以避免SQL注入问题(我没有在您的代码中更正此问题)



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;
}
&#13;
&#13;
&#13;