Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Cookie basket

Posted on 2005-04-21
13
Medium Priority
?
331 Views
Last Modified: 2006-11-18
Hi

I would like to code my basket that does everything with cookie. Most of example codes does the add, edit, remove procedure with database. I don't want to make database busy, I want to keep all the items and quantities at cookie and when customer checks out, that time write to database.

If you can please write me a code that saves items into a cookie (name, quantity, etc...) it will be excellent.

Kind regards
0
Comment
Question by:hasozduru
  • 7
  • 6
13 Comments
 
LVL 27

Expert Comment

by:Diablo84
ID: 13835123
For using cookies you need the setcookie function (see: http://us3.php.net/manual/en/function.setcookie.php )

however...

I think you will be able to make better use of sessions here. If you are not familiar with sessions have a read of: http://us3.php.net/manual/en/ref.session.php (examples further down).


Here is the basic concept:

session_start(); //must go before output to initialize the session data

$_SESSION['myvar'] = "a value"; //assigning a value to a session variable

echo $_SESSION['myvar']; //outputs "a value"

You can also use session arrays to contain data, for example:

session_start();
$_SESSION['basket'][] = "an item";
$_SESSION['basket'][] = "another item";
$_SESSION['basket'][] = "etc";

You then have an array called $_SESSION['basket'] containing 3 items.

Arrays also allow for associative indexes as well as numeric indexes. For example you could use the item ID as the key and the quantity as the value:

session_start();
$_SESSION['basket']['01234'] = 2;
$_SESSION['basket']['42524'] = 5;
$_SESSION['basket']['42323'] = 8;


Methods of outputting

With numeric indexes:

echo $_SESSION['basket'][0]; //outputs the value of the first item

(numeric indexes begin at 0 and increment by 1 for each item)

With associative indexes:

echo $_SESSION['basket']['42323'];

OR

Looping through the values:

foreach ($_SESSION['basket'] as $var) {
 echo "$var<br>\n"; //outputs the value assigned to each index
}

Looping, outputting the keys and values:

foreach ($_SESSION['basket'] as $key => $var) {
 echo "The key is $key and the value is $var<br>\n";
}


Final Example:

session_start();

//your array keys are the item id and the value is the quantity
$_SESSION['basket']['01234'] = 2;
$_SESSION['basket']['42524'] = 5;
$_SESSION['basket']['42323'] = 8;

foreach ($_SESSION['basket'] as $key => $var) {
 echo "Item Id: $key<br>\n";
 echo "Quantity: $var<br><br>\n";
}

Will output:

Item Id: 01234
Quantity: 2

Item Id: 42524
Quantity: 5

Item Id: 42323
Quantity: 8


Diablo84
0
 

Author Comment

by:hasozduru
ID: 13835558
Diablo84, you are like Lamborghini Diablo (: Thanks for your answer. Let say customer add one item to the basket, and added second one. How will I understand that there was already one item in the basket. Also if s/he wants to change quantity, how will I process it?

Cheers
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13835674
No problem :)

For adding another item, all you need is the increment operator, ++

For example, if $_SESSION['basket']['01234'] currently has the number 3 assigned to it,

$_SESSION['basket']['01234']++;

would increment its value by 1, so it would now equal 4. This is the equivalent of:

$_SESSION['basket']['01234'] = $_SESSION['basket']['01234'] + 1;

As for changing the quantity, all you need to know is the ID of the item (so you can reference the correct key) and the new quantity. For the sake of example, if you had the item Id in a form field called itemid and the new quantity in a form field called qnt the code would look something like this:

$id = $_POST['itemid'];
$_SESSION['basket'][$id] = $_POST['qnt'];

In the real situation you would probably want to validate the quantity and the id submitted to check that they are valid data.

To familiarize yourself with the functionality of sessions it's a good idea to set up a smaller scale test environment so you can experiment with what does what before putting them straight to use.

Diablo84
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:hasozduru
ID: 13837629
You are using $_SESSIONs. How will I add it to cookie so if user closes the browser and visits site another time, s/he will be able to see items it the basket.

Thanks
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13837706
Generally basket information is not stored in a cookie, if you are using user authentication (and the user is logged in) you would typically give them the option of saving their basket which would write the data to their profile, a row in the database.

A method of using cookies combined with the sessions however would be something like this:


Setting the cookie:

setcookie("mycookie",serialize($_SESSION['basket']),time()+3600);


Restoring the basket:

if (!isset($_SESSION['basket'])) $_SESSION['basket'] = unserialize(stripslashes($_COOKIE['mycookie']));


The serialize function allows the array to be stored as a string, unserialize effectively restores the array.

Note: I would restrict the cookie setting to being done on request, eg. provide them with a link to click to save the basket, otherwise you are going to be resetting the cookie on every page load which somewhat defeats the purpose of using sessions. If you was to have a link, <a href="page.php?savebasket">Save your basket</a> you can then set the cookie using:

if (isset($_GET['savebasket'])) {
 //set the cookie
}

Relevant links:

setcookie: http://us4.php.net/manual/en/function.setcookie.php
serialize: http://us4.php.net/manual/en/function.serialize.php

Diablo84
0
 

Author Comment

by:hasozduru
ID: 13837837
I know above but I would like to see a code like customer add items to the basket and update them.

Thanks
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13838010
It's not a good idea to use cookies in that fashion because a big basket means there will be more data to be stored in the cookie, sessions are a better approach or even saving their data in a database with an ID number and save their ID number in a cookie.

Besides that, the previous code pretty much handles the process, the item ID's are stored as the keys, the quantities are assigned as the value and the cookie code above stores the data from the session array (ie. all of the basket information) in a cookie so it can be read later to restore the session array.

If you are referring to directly interacting with the cookie throughout the users browsing session it will mean on every page that they add something to the basket you will have to read the current data from the cookie, restore the array, add the new item to the array, re-serialize the data and set the cookie again. If you are looking for efficiency in your code this is not the best approach i'm afraid.

The best you could do is:

if (isset($_SESSION['basket']) && is_array($_SESSION['basket'])) {
 setcookie("mycookie",serialize($_SESSION['basket']),time()+3600);
}

at the top of each page after session_start(); to keep the cookie data in sync with the data in the session array.

Diablo84
0
 

Author Comment

by:hasozduru
ID: 13838273
Most of big shopping sites like dabs.com saves the basket in the cookie because if you add something and you visit the site 2-3 days later, it is still there. It is convenience for customers. Is there another way of doing it?

Thanks
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13838388
Just because the data is still there by appearence it doesn't mean the basket data is stored in the cookie, it's more likely they store the data in a database and assign it an ID, that ID will be stored in the cookie to identify you next visit.

A quick trip to dabs.com and a few items added, this is the cookie content:

Version=1.2&PUID=4975feff-xxxx-xxxx-8e0c-b08084a82363&Locale=UNI2&ShowExVAT=True&SalesID=&BusinessCustomer=

Stripping away the other content you are left with:

PUID=4975feff-xxxx-xxxx-8e0c-b08084a82363

Likely to be an ID used for reference, but not the contents of the basket.

If you really want to do it this way i can give you an example but it doesn't really make sense to do this when there are more efficient alternatives available to you.

Diablo84

0
 

Author Comment

by:hasozduru
ID: 13839510
Thanks Diablo84

You have been very helpful. I understood the best way of doing it but if you could please give me the cookie way as well, I have it as an additional information.

Cheers
0
 
LVL 27

Accepted Solution

by:
Diablo84 earned 2000 total points
ID: 13841382
If you want to use cookies at all it is really better to use the cookie/session approach because then it removes the need for some of the processing (ie. reading the data from the cookie, converting it to a useful form etc). The following is a cookies only example but, again, i must stress it is not the best way to do this, far from it:

<?php
if (isset($_COOKIE['mybasket'])) $myarray = unserialize(stripslashes($_COOKIE['mybasket']));

if (isset($_POST['submit'])) {
 $itemid = $_POST['itemid'];
 $myarray[$itemid] = $_POST['qty'];
 setcookie("mybasket",serialize($myarray),time()+2629743);
 header("location: ".$_SERVER['PHP_SELF']);
 exit;
}

if (isset($myarray)) {
 echo "Items in Basket:<br>\n";
 foreach ($myarray as $key => $var) {
  echo "Item Id: $key<br>\nQuantity: $var<br><br>\n";
 }
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Item ID: <input type="text" name="itemid"><br>
Quantity: <input type="text" name="qty"><br>
<input type="submit" name="submit" value="Submit">
</form>

Take note that A) this is only a simple example to show you how it might work and B) two functions used, setcookie and header MUST go before any output otherwise the code will error.

Regards,

Diablo84
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 13867518
hi hasozduru,

Did you need any more input on this question?

Diablo84
0
 

Author Comment

by:hasozduru
ID: 13871197
Hi Diablo84

Sorry I forgot to close the question. I am doing it now.

Thanks for your answers.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 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