druhoytza979667566 2017-07-26 12:48
浏览 73
已采纳

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

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>
  • 写回答

1条回答 默认 最新

  • dongleiqiao2107 2017-07-26 12:57
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳