• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 71259
  • Last Modified:

Session Array for Shopping Cart

Hi,
I have two simple questions on session arrays.  I have created a session array for a shopping cart see below for the code [1].
When a user clicks on a url it adds the data to the session array.  The problem is I want it to only add unique products (i.e. ones which have not been added to the cart beforehand, products which already have been added to the cart I want to just add one to “qty” and increase the price of the specific productId so we don’t have duplicates in the session array).
The problem is I’m not sure how to this (see [2] for the code I has written so far, could you give me any help of what I have to do?)
 
[1]
$_SESSION['cart'][] = array(
                                           "qty" => $qty,
                                           "productId" => $prodID,
                                           "price" => $prodprice,
                                           "prodName" => $prodname
                                        );


[2]
//is session array has been set, then check that the product we are adding has not been added beforehand
if(isset($_SESSION['cart']))
{
      foreach($_SESSION['cart'] as $cartItems)
      {
        //If we have the product already
       if ($cartItems['productId'] == $prodID)
      {
      // *****Code needed to be added here*******
      // Change the product details in the session array (cart) by adding        
      // 1 to quantity (qty) and change the total price of the specific product                  
                  
            }
            // if we don’t have duplicates add the product to the session array
            else
            {
                  $_SESSION['cart'][] = array(
                                           "qty" => $qty,
                                           "productId" => $prodID,
                                           "price" => $prodprice,
                                           "prodName" => $prodname
                                        );

            }
      }
}

//if the session array has not been created beforehand create cart session array
else
{
            $_SESSION['cart'][] = array(
                                           "qty" => $qty,
                                           "productId" => $prodID,
                                           "price" => $prodprice,
                                           "prodName" => $prodname
                                        );
}

Also if I needed to delete a specific product i.e. a product with productId=1, in a the session array ($_SESSION['cart'][]), how would I do that?


Kind Regards!

Thank-you!

0
Chris_Anderson
Asked:
Chris_Anderson
  • 4
  • 2
  • 2
  • +1
1 Solution
 
AndyCommented:
I've just created my first shopping cart for my girlfriends website. I'm not saying it's the best way to do it but here goes....

Firstly, I didn't use an associative array for the basket, I used a string.

eg: "prodid1;quantity1:prodid2;quantity2 etc..."

You don't really need to store the price and product name in the session variable because you can pull them out of a database using the prodid as a reference when the user views their basket. Keeps it nice and simple that way.

So when the customer clicks 'Add to basket' I call my addtobasket.php which splits the string by : into an array which gives me my items as prodid;quantity. Then using a For... Next I iterate through the array and split up the prodid and the quantity. If it comes across a matching prodid it adds 1 to the quantity and then rebuilds the string. If it doesn't it adds :newprodid;newquantity to the end of the string.

To delete an item form the basket is very similar... split the string, iterate through the array and build a new string form the array items that you want to keep.

If you need to see my messy code just say and I'll post it.

Now I'm going to await the flaming of my methods! :)

0
 
waygoodCommented:
its easier with the associated array but use the products unique productID as the reference

ie $_SESSION['cart'][$productID]=$product_details;
where $product_details is an array of the vaues you have in the question, to save my typing it all.


then you can :-
if(isset($_SESSION['cart'][$productID]))
{
   // either do nothing, report an error OR add a futher lot again(method I prefer).
   $_SESSION['cart'][$productID]['qty']+=$product_details['qty'];
}
else
{
   $_SESSION['cart'][$productID]=$product_details;
}
the same can then be done for deleting and amending products easily.

p.s. you can convert the whole thing to a string (implode) for storing in a database later (order history).
This way your records remain accurate and will not alter when you change a price.
0
 
waygoodCommented:
p.p.s.
serialize and unserialize may be better than implode and explode as there would be less work to do.

This means you can store a cart/order for retrieval later. But (not recommended) if you store it in a cookie you will need to stripslashes first.
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
waygoodCommented:
Oh and dont increase the price of the product, this leaves less to mess around with. Keep the price as the price of a single product and then work out the total at the end (qty*price).
This way you only need to pass the reference and the qty to your functions

ie

function add_product($productID, $qty=1)
{
  if(isset($_SESSION['cart'][$productID]))
  {
    $_SESSION['cart'][$productID]+=$qty;
    return TRUE;
  }
  else
  {
    $sql="SELECT * FROM products WHERE productID=".$productID;
    $result=mysql_query($sql);
    if(mysql_num_rows($result)==1)
    {
      $product=mysql_fetch_assoc($result);
      $product['qty']=$qty;
      $_SESSION['cart'][$productID]=$product;
      return TRUE;
    }
    return FALSE;
  }
}

this way only passing product and qty reduces the chances of people interfereing with the cart.
0
 
FathomXCommented:
I know i'm reviving something long dead, but what if I wanted to want to call the data in $_SESSION['cart'][$productID] and use it to query a database. How would I do that?
0
 
waygoodCommented:
Since $productID is the key field then just use that to query the database:-

$sql="SELECT * FROM products WHERE productID=".$productID;

or if you just want to go through the cart and check each item:-

reset($_SESSION['cart']); //reset internal pointer to start of array
while(list($key,$value)=each($_SESSION['cart'])) // step through each element in the array (items in cart)
{
  $sql="SELECT * FROM products WHERE productID=".$key;
  ///// other processes here
}
0
 
FathomXCommented:
that works, thanks SO much!
0
 
teamsunarcCommented:

hghg

Open in new window

0
 
teamsunarcCommented:

hghg

Open in new window

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now