Solved

Session Array for Shopping Cart

Posted on 2004-03-20
9
70,959 Views
Last Modified: 2013-12-12
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
Comment
Question by:Chris_Anderson
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 6

Expert Comment

by:Reapz
ID: 10644333
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
 
LVL 9

Expert Comment

by:waygood
ID: 10645716
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
 
LVL 9

Accepted Solution

by:
waygood earned 20 total points
ID: 10645731
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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 9

Expert Comment

by:waygood
ID: 10645773
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
 
LVL 1

Expert Comment

by:FathomX
ID: 20378753
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
 
LVL 9

Expert Comment

by:waygood
ID: 20380755
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
 
LVL 1

Expert Comment

by:FathomX
ID: 20382391
that works, thanks SO much!
0
 

Expert Comment

by:teamsunarc
ID: 23999901

hghg

Open in new window

0
 

Expert Comment

by:teamsunarc
ID: 24000001

hghg

Open in new window

0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
How important is it to take extra precautions to protect your online business? These are some steps you can take to make sure you're free of any cyber crime.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question