添加已经在 $_SESSION 数组中的产品

Adding products that already in $_SESSION array

我在将产品添加到全局数组时遇到了一个小问题。这可以在购物车中使用。这是我们关注的代码部分:

if ( isset($_POST['id']) ){ // If the product is adding to cart. This product Id is sended via form.
            $productid = mysql_real_escape_string($_POST['id']); 
            $cartproduct = mysql_query("select * from stuff where id = '$productid'");
            $Addrow=mysql_fetch_assoc($cartproduct);
            if ($Addrow['qty']<$_POST['qty']){      // the product quantity that will add to cart can't be greater than in database
                $_POST['qty']=$Addrow['qty'];
            }

                $new_product = array(array('name'=>$Addrow['name'], 'id'=>$Addrow['id'], 'price'=>$Addrow['price'], 'qty'=>$_POST['qty'])); // Creating new product info in array
                if (isset($_SESSION['cart'])){ // If the cart exist
                    foreach ($_SESSION['cart'] as $add_product){
                        if ($add_product['id']==$_POST['id']){ // checking that product is already in $_SESSION
                            $exist = TRUE; 
                        }else{
                            $exist = FALSE;
                        }
                    }
                    if ($exist == TRUE){ // If The product is in the $_SESSION: Update amount
                        // I dont have code for it.     
                    }else{ // The product is not in array, add it.
                        $_SESSION["cart"] = array_merge($_SESSION["cart"], $new_product);
                    }
                }else{ // If the cart is not exist
                    $_SESSION['cart']=$new_product;
                }
        }

问题是当我尝试添加数组中已有的产品时。该功能正在将其添加为新产品...

第二个问题是删除这些产品。我不能用这个来做到这一点:

    foreach ($_SESSION['cart'] as $remove){
            if($_GET["id"] == $remove['id']){
                unset($_SESSION["cart"][$remove]);              
            }
        }

谁能帮忙解决一下?

我建议稍微更改数组。在 'cart' 中,使用产品 ID 作为产品的键。这样,您就可以轻松地在数组中查找和更新产品。

您可以在会话中更改购物车数组。因为键在数组中是唯一的,所以为键设置一个值会覆盖之前的值。

所以我添加了您的内部代码的一个稍微修改过的版本。它执行三个步骤:

  1. 将post变量添加到普通变量中。我发现这更容易使用,您可以在继续之前进行各种其他检查(例如检查数量是否 > 0 等)。

  2. 从数组中获取现有产品或初始化新产品。这使用 array_key_exists,因为我认为这是最纯粹的检查,但人们也使用
    isset($_SESSION['cart'][$productId]),这也应该有效。无论如何,这样的检查比使用循环更好(更快、更容易),但只有当您切换到使用产品 ID 作为密钥时它才会起作用。

  3. 只需设置或更新数量并将更新后的产品写回数组即可。如果该产品之前存在,它将覆盖之前的值。

代码变为:

// Use a variable. It's easier and more readable.
$productId = $_POST['id'];
$quantity = $_POST['qty'];

// Your other checks go here. Left out for brevity.

// Get the current product from the cart, if it exists.
// If not, create a new product.
if (array_key_exists($productId, $_SESSION['cart'])) {
  // Product found, get it and update its quantity.
  $product = $_SESSION['cart'][$productId];
  $product['qty'] += $quantity;
} else {
  // Product not found. Initialize a new one.
  $product = array(
        'name' => $Addrow['name'], 
        'id' => $Addrow['id'], 
        'price' => $Addrow['price'],
        'qty' => $quantity);
}

// Write updated or new product back to the array, and use the product id as key.
$_SESSION['cart'][$productId] = $product;

一些其他提示:

  • 如果有机会切换到 mysqli 或 PDO,请不要使用 mysql_* 函数。 mysql 函数已弃用。
  • 确保检查查询结果。可能出了什么问题(或者有人伪造了请求),数据库中找不到产品 ID。在这种情况下,$Addrow 可能会是 falsenull。请务必检查并显示适当的错误,而不是更新购物车,这可能会损坏您的购物车。
  • 如果数量加不上去,我不会默默降低数量,因为用户会认为发现了bug。相反,明确表示没有这样的数量。
  • 您可能需要重新考虑一下。毕竟,也许其他库存会在今天交付,或者其他人可能会同时订购最后一件商品。所以最好等订单保存好,要处理的时候再查看。
  • 显示有关购物车中可用数量的信息将使您的竞争对手了解您的库存量,他们也可以从中推断出其他信息。此外,他们甚至可能会下假订单,使您的网站上无法提供产品。这是一个狗咬狗的世界。请注意您显示的信息。