Php 添加已在$\u会话阵列中的产品

Php 添加已在$\u会话阵列中的产品,php,session,cart,shop,Php,Session,Cart,Shop,我在将产品添加到全局阵列时遇到了一个小问题。这可以用在购物车上。以下是我们关注的代码部分: 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_quer

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

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

有人能帮忙解决吗?

我建议稍微改变一下阵列。在“购物车”中,使用产品id作为产品的密钥。这样,您就可以轻松地在阵列中查找和更新产品

您只需在会话中更改购物车数组。由于键在数组中是唯一的,因此为该键设置一个值将覆盖上一个值

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

将post变量添加到普通变量。我发现这更容易处理,在继续之前,您可以进行各种其他检查,如检查数量>0等

从阵列中获取现有产品或初始化新产品。这使用array\u key\u exists,因为我认为这是最纯粹的检查,但人们也使用isset$\u SESSION['cart'][$productId],这也应该有效。无论如何,这样的检查比使用循环更快、更容易,但只有在切换到使用产品ID作为密钥时,它才会起作用

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

代码变为:

// 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可能为false或null。确保检查并显示相应的错误,而不是更新购物车,这可能会损坏您的购物车。 如果无法添加数量,我不会默默地降低数量,因为用户会认为他们发现了一个bug。相反,应明确说明此类数量不可用。 你可能想重新考虑一下。毕竟,今天可能会有其他库存,或者其他人可能会同时订购最后一件商品。因此,最好在订单保存良好且您希望处理订单时,稍后再进行检查。 在购物车中显示可用数量的信息将让您的竞争对手了解您的库存量,他们也可以从中推断出其他信息。此外,他们甚至可能下假订单,使您的网站上无法获得产品。这是一个狗咬狗的世界。注意你展示的信息。
经常使用。它将使您了解发生了什么以及哪里是错误的。注意:为什么在会话中存储产品的名称?您可以使用一个普通数组将id直接映射到数量。这将给你一个更干净的代码。。。
// 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;