For this week’s screencast + tutorial, we’re going to teach you how to build your own shopping cart with PHP and MySQL. As you’ll find, it’s not quite as difficult as you might have thought.
If you’re looking for a quick, ready-made solution, there are more than 50 PHP shopping cart scripts to choose from on Envato Market. Here’s a quick look at a few of them.
This is an easy-to-use, customizable PHP/MySQL-driven shopping cart. It’s equipped with two checkout options using PayPal and Submit order by Email. You can use both or either one.
Universal Digital Shop is a powerful script, which allows you to sell digital products directly on your website. It handles payments through multiple payment gateways (PayPal, Payza/AlertPay, Skrill/Moneybookers, Authorize.Net, InterKassa, EgoPay, Perfect Money, BitPay, Blockchain.info and Stripe) and can be easily integrated into any webpage.
With this widget you don’t have to install complicated shopping carts and create their design to match your website. Universal Digital Shop is the easiest way to distribute digital products and monetize a website.
This script allows you to have a quick and easy credit card payment terminal for your clients processed by stripe.com.
Installation and configuration of the script takes less than 5 minutes (however you do need to have SSL and a stripe.com account).
Symbiotic – AJAX Cart is a powerful system which can be integrated to new/old HTML websites to extend their functionality as a Cart. You don’t need to use OpenCart or any other cart for your e-commerce website. You can create your own e-commerce website in minutes using this Cart system.
Whether you use a particular CMS like WordPress or Magento or you just want to have an eCommerce site with a shopping cart built from scratch, there are plenty of expert developers on Envato Studio who will help you for a reasonable price. So if you’re stuck, head over there for the help you need.
This is just a small selection of the PHP shopping carts available on Envato Market. If those options don’t solve your problem, or if you’d rather do it yourself, let’s move on to the process of building your own shopping cart with PHP and MySQL.
Let’s begin by taking a look at the folder structure:
- reset.css – you can get the reset from this link
- style.css – our own css file that we will be using to style our HTML markup
- connection.php – the file that will make our database connection
- index.php – the template for our shopping cart
- cart.php – the file where will able to change our products from the cart(add, remove)
- products.php – the products listing page
We’ll start by writing the html markup and then style it. So open index.php and copy/paste the code below:
As you can see, our page has two columns: the main column and the sidebar. Let’s move on to the CSS. Open the file style.css and type the code below:
Here’s how our products page should look now:
Before we move on to the PHP/MySQL part, we need to create the database. So open phpMyadmin and follow these steps:
- Go to the Privileges tab, click the add new user button, and use the following settings: Username: tutorial; Host: localhost; Password: supersecretpassword;. Now make sure the Global privileges is set; then move on to the next step.
- Create a new database called tutorials.
- Create a new table called products and set the number of fields to 4. Now populate those fields so you have: id_integer – make sure it’s set to INT and mark it as PRIMARY(also set it to auto_increment); name – make it VARCHAR with a length of 100; description – VARCHAR with a length of 250; price – make sure it’s set to DECIMAL(2,6)
- Populate your table with some sample products
To save some time, I’ve exported my products table so that you can simply run the following query:
Before we move to extracting data from the database, I’ll make my index.php a template for the product list and cart. So add the following code to the top of your index.php page:
- session_start() – this is for later use; it will allow us to actually use sessions (it’s vital that the session_start is written before any other data is sent to the browser).
- On the second line, we include the connection.php that will establish the connection to the database (we will deal with this in a second). One more thing: the difference between include and require is that if you use require and the file can’t be found, the script execution will end. If you use “include”, the script will continue working.
- Instead of copying the entire html code(the link to the css, to the js) for every file in your site, you could just make them all relative to a single file. So first, I’m checking if there’s a GET variable called “page set”. If it’s not, I’m creating a new variable called _pages. If the GET variable called pages is set first, I want to make sure that the file which I’m going to include is a valid page.
To make this work, we need to include the file; add this line to the index.php between the div with the id of “main”:
Now here’s the complete index.php we have now:
Let's create the connection to MySQL. Open connections.php and type the following:
Now it's time to write the markup for the products page. So go ahead open it and type the following:
Let's take a look at the page:
As you can see, it's pretty ugly. So let's style it by adding this extra CSS.
Okay: let's have another look now:
Looks a lot better, don't you think? Below you have the complete style.csscode:
Before we extract the product from the database, let's remove the last 2 table rows from our table(we used it only to see how our table will look like). Remove this:
Great! Now in the place where the table rows were, type the following PHP code:
- So, first we use SELECT to retrive the products, then we loop trough each row from the database and echo it to the page in a table row.
- You can see that the anchor links to the same page(when the user clicks the anchor the product it's added to the cart/session). We just pass some extra variables like the id of the product.
If you hover one of the add to cart links, you can see, at the bottom of the page, that the id of the product is passed.
Let's make that anchor work by adding the following code at the top of our page:
- If the GET variable called action is set and it's value is ADD, we execute the code.
- We make sure that the id passed through the GET variable is an integer
- If the id of the product is in the cart SESSION, we just increment it's quantity by 1
- If the id is not in the session, we need to make sure that the id passed through the GET variable exists in the database. If it does, we grab the price and create it's session. If it doesn't, we set a variable called message that will hold our error.
Let's check if that message variable is set and echo it to the page(type this code under the H1 page title):
Here you can see the complete products.php page.
Here's the error message if the id of the product is invalid
Let's go back to the index.php and build the sidebar. Add the following code:
- First we check if the session cart is set. If it's not, we display the message, alerting the user that the cart is empty.
- Next we make a mysql SELECT, but we're selecting only the products that exists in the session too. To accomplish this, we use the foreach function. So we are looping through the session and are adding the product id to the SELECT. Next, we are using the substr function to remove the last comma from the SELECT.
- In the end we output the data to the browser.
Take a look at the pictures below:
Since the index.php is a template for all the files, the sidebar will be visible in the cart.php too. Ain't that cool?!
Finally, open cart.php and start by typing the following code:
The code is similar to the one from index.php and products.php, so I'm not going to explain everything again. You should notice that instead of displaying the quantity in a form, now it's displayed in an input box (so that we can change the quantity). Also the table is wraped in a form tag.To get the total price of the items we multiply the quantity of the specific product(from the session) id with it's price. This is done in each loop.
NOTE: The input is an array, the key is the id of the product, and the quantity is the quantity value.
The last step we need to do is to make the form work. So add this code to the top of the cart.php page.
- First we check if the form was submitted. If it was submitted and the value of the input was zero, we unset that session.
- If the value is any other value, we set the quantity to that value instead.
Here is the complete cart.php