As is promised some time ago, i started writing tutorials about basic programming concepts exclusively for insanelyart.com;
This is the first tutorial of my upcoming collection and i hope that admins will approve it, but not least, i hope that it will be useful to someone and that you will like it.
In this tutorial i will show you how a basic shopping cart works, and how to build your first PHP shopping cart.
First of all, let's imagine a supermarket crowded by people buying goods. Every client has it's own shopping cart and that's why we need to keep track of everyone's purchases without mixing them up with each other. The simplest way to do this is giving every shopping cart a unique ID. The products that the clients will buy will also have a unique ID. Finally, we will have to link the single shopping cart with the client. In this following example, users do not need to register to shop so we will not have a list of users to link user name and shopping cart ID. We can use several other methods instead, but i will explain this further during the tutorial. The next image is a schema of what written up here:

In the upper illustration you can see three tables, everyone used to store different information.
We have a table that contains data about every item, with a random generated ID, like:
ID: 47JER32DN0
NAME: Water Melons
PRICE: 1,95
DESCRIPTION: Fresh water melons. Country of provenience: Turkey.
The ID is also the primary key of the table witch means that it can not be duplicated (it will be impossible to have two items with the same ID).
The table that contains data for every shopping cart is made pretty much like the items table, every shopping cart having it's own unique ID, so there can not be two shopping carts with the same ID, just like the items.
After building the two tables, we have to link it with each other and for that reason we will need a third table called rel because we need a many to many kind of relationship. A many to many kind of relationship stands for 1 item can be found in more than 1 shopping cart, 1 shopping cart can contain more than 1 item.
The table rel has a primary key composed of two elements that can not be duplicated together. To make more sense out of it, take a look at the image bellow:

The section in red shows what explained earlier.
Ok, it's time to create the three tables using the code bellow:


Pay attention at the data types used for the creation of the tables.
The id's are VARCHAR(10) which means that the ID will be alphanumerical composed of 10 characters and that it can not be null. Another important thing is that the connected fields between the tables must be the same data type.
The price of every item is FLOAT data type so we can store prices with decimals.
Download the code and insert it into your MySql. You should obtain:

Congratulations! You have now created the basis of your shopping cart. What's left to do is linking every single shopping cart with the client.
Considering that the users do not need to register in to place an order, we have to think about how to resolve this problem. A way of doing it is to link the tutorial's ID with the user's IP address, but what about users that have a dynamic IP address that changes every time they connect? This means that the link between the user and it's cart will be lost.
Another way of linking users and carts without forcing the user to register is through cookies.
You can set a cookie containing the shopping cart's ID related to the user and ask for the cookie every time the user accesses you website.
Watch the following example of code:


In case the cookie is not set, you can choose to create the user's personal shopping cart when he adds an item to it for the first time, or as soon as he visited your website for the first time.
I will create the shopping cart as soon as he accessed the page using the code bellow:


The function that generates the ID code could be built like this:


I have chosen to set the lifetime of the cookie for one month, so the user can still view the items he added to the cart even after a month (you can set it for an year if you want to).
If the user already has a shopping cart linked to him, we can perform several tasks in order to build the content of the page.
For example, we can count the number of items he has added into it, we can calculate the total expense he is heading to, we can see exactly what items he chosen to buy.
Remember that the table items is connected to the table carts so i will give you an example of how to view the content of the user's shopping cart. Take a look at the code bellow:


Of course, this is not the only thing you can do, but i will show you more interesting stuff in the next part of the tutorial, so this is about all for today.
Stay tuned and come by tomorrow and i will show you how to add items to the shopping cart, how to delete items from the shopping and how to place an order with the content of the shopping cart.
If you want to see this shopping cart at work, you can visit bijushop.asoc.ro .
I will consider providing this script for free as after i will have written all the parts of the tutorial.
For now, i will only provide a piece of code related to this part of the tutorial.
I hope you enjoy it and do not be shy to post a comment if you have further questions.
Let's imagine the user visiting our website and getting interested in buying one or more items.
We will follow several steps between the access of the user on the page and the final placement of the order.
In the previous part of the tutorial we saw that as soon as the user visits your site, the visited page verifies if the user has a shopping cart already set and if not, it proceeds to setting the user's personal cart.
After that routine check, we can build the page that the user will see, just like in the example bellow:

In the left side of the screen we can place the items along with buttons in order to perform several commands. As you can see, we display an image for every single item, so we are going to need another field into the items table to store the image's URL.
What you have to do, is alter the table by inserting the newt code into your MySql:


Now we can finally build the page!
To do so, we need to access the database and extract the information that we will send to the browser.
Watch the code bellow:


I have extracted only the information related to the items and now we need to add the functionalityes.
Let's start with adding items to the shopping cart.
In order to do this, we need to send a request to a page that will perform the task. The request can be sent in many ways (a form that uses POST as method, a link that passes the information through URL, also known as GET method).
I will use the second choice so the example will be more obvious and easy to understand.
Now, remember that when we extracted the information, we also extracted the ID of every single item from the database. Because it's the unique identifier of the item, we will use this ID in the request along with other information that the page will need in order to understand what it has to do with it.
The request could look like this: www.mywebsite.com/mypage.php?action=add&item=H69FGS42S5
The page mypage.php is accessed and it receives two parameters (action and item) through GET method. Once the page is accessed, we have to do several checks to process the task.
Take a glance at the code bellow:


I have decided to use a switch because, further on I will add another action (the delete one).
Let's focus to the add action now.
Once the page knows what kind of request it got, you need to build the code that will perform the selected request.
Remember that the ID of the desired item was also passe to the page and now all you have to do is link the passed ID of the item with the ID of the user's shopping cart.
We will ask for the cookie containing the shopping cart ID and after that we will perform the MySql query that links the cart with the item.
This is the code to do it:


Anyway, the code is incomplete. We have not passed the number of items.
Resuming what said until now, we can assemble the whole code, assuming that the request will look like www.mywebsite.com/mypage.php?action=add&item=H69FGS42S5&quantity=1


You should now obtain something like this:

Now the user's shopping cart contains the selected item. Congratulations!
Let's see now how we can send the request.
The request will have a different URL for every specific item, according to the item's ID and quantity.
To launch a request we need to build the link for every request dynamically, when we start building the page.
Here is an example of code:


The resulting page will look like this:

Very good! You have sent the request, you have registered the new data, all you have to do now is show in the right upper corner the number of different items contained in the shopping cart.
All you have to do is a simple query like this, and print the resulting information to screen:


Friends, this is kind about all reguarding add elements to the shopping cart.
I will show you now how to delete an item from the cart.
Just like in case of the add process, we have to send a request to a page.
We will use GET method for this too. The request URL could look like this: www.mywebsite.com/mypage.php?action=delete&item=H69FGS42S5
Unlike the add request, the delete request does not have to contain the number of items.
Take an overview of the beginning of this tutorial and you will notice the switch showed before. I will add another case to that switch so that the page can make the difference between the requests and that it can perform the requested task.
After adding the code, the block will look loke this:


Inside the case selector we will add the code that will perform the task.
It could look like this:


Finally, the whole block of code, now looks like this:


When building the HTML on the page, the link for the delete request could be built like this:


Depending on your needs, you can choose which one of the links to show when assembling HTML (or maybe both of them.)
Having finished this part of the tutorial, i will show you how to place an order, how to count the total amount of the client's expense, how to change the number of items per every item inside the shopping cart and much more. All of these questions, in the next part of the tutorial.
First of all, let's take a small review upon what said in the previous parts.
1. The visitor enters your website.
2. Every single page contains the code that verifies if he has already a cart associated to him.


3. In case he doesn't have a shopping cart, we launch the block of code that creates his personal shopping cart, at the beginning, empty.


4. Once we have a shopping cart, we ask for the ID of the shopping cart contained into the COOKIE and we count the number of items associated with the cart.


5. We display the items contained in the database according to the items associated with the shopping cart (if the item is not associated with the cart we can display the Add to cart button. Else, we can display the Delete from cart button).
* Ask for the cart ID
* Extract all the items from the database
* For every single item, verify if the item's ID is associated with the shopping cart's ID
* Display the information


6. We provide the code that the page will use in order to filter the requests coming and perform the required tasks (the switch with the containing code)


To understand better the way that the user is linked to the items he bought, take a look at the illustration bellow:

Now, we will see how to build the page that displays the content of the cart and how do we place an order.
Let's suppose that the page is named mycart.php
When the user enters the page we have to display only the items he selected to make part of his cart.
The items table and the carts table are linked through rel table.
For that reason, we will retrieve the shopping cart's ID from the cookie, and we will select the item ID's that are linked to it inside the rel table.
After that, for every single item ID, we will extract the item details from items table.
To do that we use the code:


The resulting page will looke like this:

Considering that the displayed elements are all contained inside the cart, we can also display for every item the Delete from cart button, adding the following code:


Now, the whole code has become like this:


This way, the user will be directed back to mypage.php. If you want to avoid this, you can set inside the form action the value mycart.php and add to the page the code that filters the requests and does the required action. Watch part two
Very good! You are doing great!
What's left to do is adding another function to the page. I am talking about the function that can modify the item quantity selected by the user, without having to delete the item and add it again, directly from cart.
To do this, we need to display the item quantity in a text input, contained in a form along a submit button.
I will use GET method for this too.
The form would look like this:


By assembling this piece of code with the rest, we obtain the final "display rules" for the mycart.php page
It all looks like this:


Just as on mypage.php, we have to different possible requests, so we need to place the code that does the difference between them.
It looks like this:


After adding the code that will handle the requests inside the switch cases, the whole code looks like this.
Note that the switch code must be placed inside the page before the code that builds the HTML because you must update the content of the cart before displaying it.


Now you have all the functions necessary on this page.
The page will look like this:

What's left to do is calculate the total amount and display the Place Order button
The total amount could be calculated inside the WHILE used for the display.
We create a new variable with an initial value of 0, and by every loop we add to it the value of every single item.
At the end of all loops, we can display the calculated value and the button to place the order.
I will go back to review the code and add the necessary instructions.
The resulting code will look like this:


We need to display the total price and the button.


The code that will handle the place order request will be inserted in the myorder.php page that will contain also a form where the user can insert billing address, personal data and so on.
To process the order we need a new table in which we will store the passed information
Use the following code:


You will obtain this:

The myorder.php page will retrieve the cart ID from the cookie and by doing that, will know what items have been ordered.
In other words, the orders page will link the rel table with the orders table and after doing that will delete the cookie that links the user with the cart. That way, the cart does not exist any more (in a way of speaking) and the order will be registered.
Because the cookie will be deleted, as soon as the users navigates to another page of the website he will have another cookie with another code set, so he will have a brand new empty shopping cart.
This is how our system works now:

We presume that myorder.php send the request of order registration along with client name and address via GET method.
First, we grab the shopping cart ID and the passed data.
We register all the data inside the orders table.
After doing that, we unset the cookie that contains the shopping cart ID.
Here is the code to do this.


Now the order has been placed and the user will have a new empty shopping cart.
I think this is all, my friends and i hope i have not forgot anything.
See you soon!
Download Resource

No comments:
Post a Comment