Search code examples
phpsessioncart

Adding products that already in $_SESSION array


I have a tiny problem with adding products into global array. This may be used in shop cart. Here is the part of code that we focus in:

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

And the problem is when I try to add the product that already in array. The function is adding it as new product...

The second problem is with remove these products. I can't do this using this:

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

Anyone can help to solve it?


Solution

  • I would suggest to change the array a bit. Inside 'cart', use the product id as a key for the products. That way, you can easily find and update products in the array.

    You can just change the cart array in the session. Because keys are unique in the array, setting a value for the key will overwrite the previous one.

    So I've added a slightly modified version of your inner piece of code. It performs three steps:

    1. Add the post variables to normal variables. I find this easier to work with, and you can do all kinds of other checks before continuing (like checking if quantity > 0 etc).

    2. Get the existing product from the array or initialize a new product. This uses array_key_exists, because I think that's the purest check, but people also use
      isset($_SESSION['cart'][$productId]), which should also work. Anyway, such a check is better (faster, easier) than using a loop, but it will only work if you switch to using product ids for the keys.

    3. Simply set or update the quantity and write the updated prodct back into the array. If the product existed before, it will just overwrite the previous value.

    Code becomes:

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

    Some other tips:

    • Don't use the mysql_* functions if you have the opportunity to switch to mysqli or PDO. The mysql functions are deprecated.
    • Make sure to check the query result. Maybe something went wrong (or someone forged a request), and the product id cannot be found in the database. In that case, $Addrow will probably be false or null. Make sure to check for this and display an appropriate error instead of updating cart, possibly corrupting your cart.
    • If the quantity cannot be added, I wouldn't silently lower the quantity, because the user will think they found a bug. Instead, clearly state that such a quantity is not available.
    • And you may want to reconsider that. After all, maybe other stock will be delivered today, or other people might order the last item simultaneously. So it's better to check it later, when the order is well saved and you want to process it.
    • Showing information about available quantities in the cart will give your competition insight in the amount of stock you have, from which they can deduce other information too. Also, they may even place fake orders to make products unavailable on your website. It's a dog-eat-dog world. Be careful what information you show.