For the simplicity of this example I am using four separate arrays and some additional variables. The code can be optimized. This makes it easier to display the idea and to read the code. This could be done better with a class, but I am not quite sure if you can store objects into sessions. Someone comment on this?
We also need an item counter. Of course this could be done with the count() command, I just thought it would be nice to always know how many items there are, and it gives a nice counter for loops too.
Let's assume you have a listing of articles in your html page:
|ID|| Name|| Price|
|1|| Mouse|| 25.00 add|
|2|| Key|| 100.00 add|
|3|| Car|| 5000.00 add|
|4|| Game|| 25.00 add|
Adding the Link to Your Page
The 'add' field is the link to place items into the mini basket. Point this link to itself using the
$PHP_SELF variable. Then add the article information to it. Here's the example for article 1.
<A HREF="<?echo $PHP_SELF;?>?id=1&price=25&basket=Mouse">add</A>
Article Names can contain spaces, so put it at the last position in your link. The get method seems to be picky about this.
Preparing the Minibasket
For reusability, lets create an external file minibasket.inc. I use the .inc extension to mark my include files. The reason to put this external is, even though you will be passing the basket on using session variables, the code still needs to be available.
The file will contain the code to display the mini basket, and the function to add items to it. Best place to implement this is to put the:
<?php include ("minibasket.inc"); ?>
command right there where you need it.
The Logic of the Minibasket.inc
Spend some time thinking about this. What should the minibasket look like, what features does it need? The minibasket displayed here would look something like this:
|1|| Mouse|| 25.00|
|3|| Game|| 75.00|
| Total|| 100.00|
You can easily format this output using an external style sheet. It should not be too big, though. This minibasket is information, yet it is not the focus of the page you are showing.
The logic of the file is very simple.
Check if a new item needs to be added.
If true, add the item.
Within the adding it looks for duplicate entries and updates the existing entry by updating amount and pricing information.