Question

Session Array for Shopping Cart

Asked by: Chris_Anderson

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!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-03-20 at 15:26:06ID20926089
Tags

session

,

array

Topics

PHP and Databases

,

E-Commerce

,

Payment Processing Recommendation and Integrating

Participating Experts
4
Points
20
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. shopping carts
    hi i'm trying to develop my own shopping carts. actually, at this moment, i can say it as "quotation cart". ok. i've developed my own website and it has more than 500 products. i don't have a server(i just rent it for only 100 dollars a month). i also don't have my ...
  2. Shopping cart
    I am trying to get some information from a database into a table in HTML form. It is in the form of a shopping cart. So how do I use ASP code, using VBScript as the default language. For example the fields are ProductName, Unitprice, Quantity,etc. I am using Microsoft FrontPa...
  3. Shopping Cart
    I posted my problem in the other forums and the people there did not help me very much! I am working on a shopping cart in ASP. I have downloaded a few free shopping cart source codes, but they are too difficult for me. I have only 4 months experience in ASP. Do you have an...
  4. Shopping Cart
    Dear All Experts, Now i'm doing a project for a web-base shopping cart. I got a list of products, user can buy my products from web. Now i wanna to do a shopping basket for user to add in all the product in the basket. but i dun want the user add each product in db. only whe...
  5. PHP Associated Array - shopping cart
    I am setting up a basic shopping cart and at present I have the folowing code to store the product_id and quantity of those items which the customer has chosen to add to the basket: $product_details = array("qty" => $quantity, "productID" => $prod...
  6. Errors in shopping cart
    I am getting this error when I used a fix for a addon. Below is the function that contains the error. What do I need to change to fix this or what kind of information do you need to answer this question? Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ReapzPosted on 2004-03-21 at 08:40:01ID: 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! :)

 

by: waygoodPosted on 2004-03-21 at 15:10:56ID: 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.

 

by: waygoodPosted on 2004-03-21 at 15:15:32ID: 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.

 

by: waygoodPosted on 2004-03-21 at 15:25:00ID: 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.

 

by: FathomXPosted on 2007-11-29 at 16:30:51ID: 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?

 

by: waygoodPosted on 2007-11-30 at 02:20:15ID: 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
}

 

by: FathomXPosted on 2007-11-30 at 07:01:29ID: 20382391

that works, thanks SO much!

 

by: teamsunarcPosted on 2009-03-27 at 05:03:08ID: 23999901

hghg

                                              
1:

Select allOpen in new window

 

by: teamsunarcPosted on 2009-03-27 at 05:17:05ID: 24000001

hghg

                                              
1:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...