[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Session Array for Shopping Cart

Posted on 2004-03-20
9
Medium Priority
?
71,194 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
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 6

Expert Comment

by:Andy
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 80 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The Internet has made sending and receiving information online a breeze. But there is also the threat of unauthorized viewing, data tampering, and phoney messages. Surprisingly, a lot of business owners do not fully understand how to use security t…
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…
Suggested Courses
Course of the Month18 days, 1 hour left to enroll

831 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