Solved

Session Array for Shopping Cart

Posted on 2004-03-20
9
70,793 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:Reapz
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 9

Expert Comment

by:waygood
Comment Utility
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
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Expert Comment

by:FathomX
Comment Utility
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
Comment Utility
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
Comment Utility
that works, thanks SO much!
0
 

Expert Comment

by:teamsunarc
Comment Utility

hghg

Open in new window

0
 

Expert Comment

by:teamsunarc
Comment Utility

hghg

Open in new window

0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Read about how to choose the best possible content marketing agency to suit your needs. Content marketing has become an integral part of running a successful tech business, so it is wise to be informed.
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…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

743 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now