Shopping Cart Code Php Free Download

This tutorial will walk you through how to create a simple AJAX driven PHP MYSQL eCommerce Shopping Cart - Free source code download included. Simple Shopping Cart in PHP helps the user in managing all the shopping cart. To run this project you must have installed virtual server i.e XAMPP on your PC (for Windows). The software allows online shopping customers to accumulate a list of items for purchase, described metaphorically as “placing items in the shopping cart” or “add to cart.” Upon checkout, the software typically calculates a total for the order, including shipping and handling (i.e., postage and packing) charges and the associated taxes.

In this tutorial we'll be creating a shopping cart system with PHP and MySQL. The shopping cart system will allow our websites visitors to browse for products, add to cart products, and place orders.

We'll be using the PDO extension to access our MySQL database with PHP. PDO will make it much easier for us to interact with our database, no need to download it as it will be included in the latest version of PHP.

The shopping cart system we'll be creating will contain 4 products. These products are basically just gadgets/accessories that we'll use as examples for this tutorial. You can add your own products later in the tutorial.

The Advanced package includes additional features and a download link to the source code.

Contents

  1. Getting Started
  2. Creating the Index File
  3. Creating the Home Page
  4. Creating the Products Page
  5. Creating the Product Page
  6. Creating the Shopping Cart Page
  7. Creating the Place Order Page

1. Getting Started

There are a few steps we need to take before we create our shopping cart system. We need to set-up our web-server environment (if you haven't already) and make sure we have the required extensions enabled.

1.1. Demos

Below you will find links to the shopping cart demos. The tutorial demo is what we'll be creating. The Advanced demo is the package you can purchase at the end of the post. This includes more features and a download link to the source code.

1.2. Requirements

  • If you haven't got a local web server setup you should download and install XAMPP.
  • Make sure the PDO extension is enabled (it should already be).

1.3. What You Will Learn in this Tutorial

  • Template Design — Design a home page, products page, product page, shopping cart page, and place order page with HTML5 and CSS3, and learn how to use the PHP templating system with HTML.
  • GET and POST Requests — Create HTML forms and data request handling with PHP.
  • Prepared SQL Queries — How to prepare SQL queries to prevent SQL injection.
  • Basic Validation — Validating form data that is sent to the server.
  • Session Management — Initialize sessions and store shopping cart products.

1.4. File Structure & Setup

We can now start our web server and create the files and folders we're going to use for our shopping cart system.

  • Open XAMPP Control Panel
  • Next to the Apache module click Start
  • Next to the MySQL module click Start
  • Navigate to XAMPPs installation folder (C:xampp)
  • Open the htdocs folder
  • Create the following folders and files:

File Structure

-- shoppingcart
-- functions.php
-- index.php
-- home.php
-- products.php
-- product.php
-- cart.php
-- placeorder.php
-- style.css
-- imgs
-- featured-image.jpg
-- camera.jpg
-- headphones.jpg
-- wallet.jpg
-- watch.jpg

Each file/folder will contain the following:

  • functions.php — This file will contain all the functions we need for our shopping cart system (template header, template footer, and database connection functions).
  • index.php — This file will contain the master template (header, footer, etc) and basic routing so we can include the pages below.
  • home.php — This file will be the home page that will contain a featured image and 4 recently added products.
  • products.php — This file will be for displaying all products with basic pagination.
  • product.php — This file will display a product (depends on the GET request) and will contain a form that will allow the customer to change the quantity and add to cart the product.
  • cart.php — The shopping cart page that will list all the products that have been added to cart, along with the quantities, total prices, and subtotal price.
  • placeorder.php — A basic message that will be displayed to the user when they place an order.
  • style.css — The stylesheet (CSS3) we'll use for our shopping cart website.
  • imgs — Directory that will contain all the images for our shopping cart system (featured images, product images, etc). You can download the example images by clicking the file name in the file structure container.

2. Creating the Database and setting-up Tables

For this part, you will need to access your MySQL database, either using phpMyAdmin or your preferred MySQL database management application.

If you're using phpMyAdmin, follow these instructions:

  • Navigate to http://localhost/phpmyadmin/
  • Click the Databases tab at the top
  • Under Create database, type in shoppingcart in the text box
  • Select utf8_general_ci as the collation (UTF-8 is the default encoding in HTML5)
  • Click Create

Feel free to use your own database name, or use shoppingcart as the database name.

We can now proceed to create the products table. We'll use this table to store all our products, along with the product name, description, image, price, RRP price, quantity, and the date added columns. We shall retrieve these products later on in the tutorial with PHP.

Click the database on the left side panel (shoppingcart) and execute the following SQL statement:

Shopping Cart Code Php Free Download

On phpMyAdmin this should look like:

The above SQL statement code will create the products table with the following columns:

  • id — Unique ID for the product, this will be auto incremented.
  • name — The name of the product.
  • desc — The description of the product.
  • price — The price of the product.
  • rrp — The retail pricing, if you want a product on sale you put the value higher than the price.
  • date_added — The date the product was added, we'll use this for sorting products.

The SQL statement will also insert 4 example products that will be used for testing purposes. You can change/remove them later on.

3. Designing the Shopping Cart System with CSS

Instead of using a library such as Bootstrap, I've decided to create a clean, crisp, and modern design with pure CSS3.

The Advanced package includes the SCSS file and the responsive design CSS code. You can easily change the color scheme, fonts, content size, etc, with SCSS.

Edit the style.css file and add the following code:

CSSCopy

This will be the stylesheet we'll use for the shopping cart system.

4. Creating the Functions File

The functions.php file will contain all the functions we're going to use in our shopping cart system, this includes the template header, template footer, and the database connection functions.

Edit the functions.php file and add the following:

These functions will make it much easier for us to connect to the database and format our pages. We'll be including this file in a majority of our PHP files. Instead of writing the same code repeatedly, we can easily execute the function name. We can also change the layout of our shopping cart system without editing every single file.

We're using Font Awesome (free icon library) for our font icons. The stylesheet CDN is included in the HTML head section (template header function).

5. Creating the Index File

The index.php file will basically be our main file for accessing pages. We'll set-up basic routing and use GET requests to determine which page is which.

5.1. Connect to MySQL Database

Edit the index.php file and add the following:

PHPCopy

We first create the session with the session_start function. With that we can store the products that are added to cart, subsequently, the script will connect to MySQL using the database connection function we created earlier, in the functions.php file.

Note: Update the database connection variables if you cannot connect to MySQL.

5.2. Basic Routing

Add after:

The basic routing method used above checks if the GET request variable ($_GET['page']) exists. If not, the default page will be set to the home page, whereas if it exists, it will be the requested page.

For example, if we want to access the products page, we can navigate to http://localhost/shoppingcart/index.php?page=products.

If you navigate to the index.php page in your browser the page will appear blank, that's because we haven't edited the home.php file yet.

6. Creating the Home Page

The home page will be the first page our customers will see. For this page, we can add a featured image and text, along with a list of 4 recently added products.

6.1. Get 4 Products from Database

Edit the home.php file and add the following:

PHPCopy

The above code will execute a SQL query that will get the 4 most recently added products. All we have to do with this query is order by the date_added column and limit the amount by 4, pretty simple right? And then store the result in the $recently_added_products variable (as an associated array).

6.2. Create Home Template

Add after the PHP closing tag:

This will create us a basic home page template. The above code will iterate the $recently_added_products array variable and populate them accordingly. The RRP price will be included but only if the value is greater than 0.

If you prefer to use your own currency you can change the $ entity code. You can find the list here.

Note: all the product images are located in the img directory. You'll need to download the images for those products if you're using the example products we created previously. You can download them in the File Structure section.

If we navigate to http://localhost/shoppingcart/index.php, it should look like the following:

You can also access the home page by specifying the page parameter (http://localhost/shoppingcart/index.php?page=home). This is possible because of the basic routing we implemented earlier.

7. Creating the Products Page

The products page will be where our customers will go to browse all of our products. We will limit the number of products to show on each page and add pagination that will allow the customers to navigate between pages.

Shopping Cart Php Code Free Download

7.1. Get Products from Database with Pagination

Edit the products.php file and add the following:

PHPCopy

Updating the $num_products_on_each_page variable will limit the number of products to show on each page.

To determine which page the customer is on, we can use a GET request, in the URL this will appear as index.php?page=products&p=1 etc, and in our PHP script the parameter p we can retrieve with the $_GET['p'] variable. Assuming the request is valid, the code will execute a query that will retrieve the limited products from our database.

Note: We're executing queries using prepared statements.Prepared statements will fully prevent SQL injection. It's good practice to prepare statements with GET and POST requests.

7.2. Get the Total number of Products

Add after:

The code above will get the total number of products in our products table. The customer will be able to see the total number of products at the top of the products page.

7.3. Create Products Template

Add after the PHP closing tag:

PHPCopy

Remember the recently added products we created for the home page? We basically use the same code but instead it's determined by the products page and the $num_products_on_each_page variable.

The Next and Prev buttons will only be visible to the user if the total number of products is greater than the $num_products_on_each_page variable.

If we navigate to http://localhost/shoppingcart/index.php?page=products it should look like the following:

http://localhost/shoppingcart/index.php?page=products

That's basically all we need to do for the products page, additional features such as product sorting are available in the Advanced packages.

8. Creating the Product Page

The product page will display all details for a specified product, determined by the GET request ID variable. Customers can view the price, image, and description. The customer will be able to change the quantity and add to cart with a click of a button.

8.1. Get Product from Database with GET Request

Edit the product.php file and add the following:

The code above will check if the requested id variable (GET request) exists. If specified, the code will proceed to retrieve the product from the products table in our database.

If the product doesn't exist in the database, the code will output a simple error, the exit() function will prevent further script execution and display the error.

8.2. Create Product Template

Add after the PHP closing tag:

PHPCopy

The template we'll use for the product page. The form is created and the action attribute is set to the shopping cart page (index.php?page=cart) along with the method set to post. The shopping cart page (cart.php) will add the product to cart.

With the quantity form field, we can set a maximum value, this value is set to the product's quantity (retrieved from the products table). The product ID is also added to the form, as this is so we know which product the customer added.

We don't need to include the product's name, description, etc, as we can get that data from the products table in our database with the product ID.

If we navigate to http://localhost/shoppingcart/index.php?page=product&id=1 it should look like the following:

http://localhost/shoppingcart/index.php?page=product&id=1

If you change the id parameter in the URL to let's say 2, it will show us a different product.

9. Creating the Shopping Cart Page

The shopping cart page is where the customer will be able to see a list of their products added to the shopping cart. They will have the ability to remove products and update the quantities.

9.1. Adding a Product to Cart

Edit the cart.php file and add the following:

In the code above we make use of the PHP session variables. We can use PHP sessions to remember the shopping cart products, for example, when a customer navigates to another page etc, the shopping cart will still contain the products previously added until the session expires.

The code above will check if a product was added to cart. If you go back to the product.php file you can see that we created an HTML form. We are checking for those form values, if the product exists, proceed to verify the product by selecting it from our products table in our database. We wouldn't want customers manipulating the system and adding non-existent products.

The session variable cart will be an associated array of products, and with this array, we can add multiple products to the shopping cart. The array key will be the product ID and the value will be the quantity. If a product already exists in the shopping cart all we have to do is update the quantity.

9.2. Removing a Product from Cart

Add after:

PHPCopy

On the shopping cart page the customer will have the ability to remove a product from the cart. When the button is clicked, we can use a GET request to determine which product to remove, for example, if we have a product with the ID 1, the following URL will remove it from the shopping cart: http://localhost/shoppingcart/index.php?page=cart&remove=1.

9.3. Updating Product Quantities

Add after:

The code above will iterate the products in the shopping cart and update the quantities. The customer will have the ability to change the quantities on the shopping cart page. The Update button has a name of update, as this is how the code will know when to update the quantities using a POST request.

9.4. Handling the Place Order

Add after:

PHPCopy

This will redirect the user to the place order page if they click the Place Order button.

9.5. Get Products in Cart and Select from Database

Add after:

If there are products in the shopping cart, retrieve those products from our products table, along with the following column name: product name, description, image, and price, as before we didn't store this information in our session variable.

We also calculate the subtotal by iterating the products and multiplying the price by the quantity.

9.6. Create Shopping Cart Template

Add below the PHP closing tag:

PHPCopy

That's all we need to do for the shopping cart page. The customer can now remove products and update quantities.

If you add a few products to the shopping cart and navigate to http://localhost/shoppingcart/index.php?page=cart, it will look similar to the following:

To get the quantity to display in the header you'll need to edit the functions.php file and add the following to the template header function:

PHPCopy

Find:

Add after:

And now the customer will know how many products they have in their shopping cart at all times, as this will appear on every page.

10. Creating the Place Order Page

This page will let the customer know that they have placed an order. Customer must-have products in their shopping cart and have clicked the Place Order button on the shopping cart page.

Php shopping cart project

10.1. Creating the Place Order Template

Edit the placeorder.php file and add the following:

PHPCopy

And now if we add a product to our shopping cart and click the Place Order button, we'll see the following:

Feel free to change the place order message, etc.

Conclusion

Congratulations! You've successfully created a shopping cart system with PHP and MySQL, what next? Consider adding a checkout page and integrate a payment method, such as PayPal. PayPal provide their own API for developers. You can also check out our How to Integrate PayPal with PHP and MySQL guide.

Remember that this is just a base shopping cart system for you to work from, therefore I don't recommend going production until you have made a reasonable amount of changes and additions, you would need to add your own error handling, payment method, and validation.

If you enjoyed this tutorial, don't forget to hit the share button and drop a comment, this will help us create more future content.

If you would like to support us consider purchasing the advanced package below, this will greatly help us create more tutorials and keep our server up and running.

Basic

Source code
Home page

Simple Shopping Cart In Php Source Code Free Download

Product & Products page
Checkout page
Update quantity feature
Transactions feature
Stripe Support
Order details email feature

Shopping Cart Html Code

Product categories feature
Product shipping feature
Sort products feature
Responsive design (mobile friendly)
Commented code
User Guide

View Online

Php Online Shopping Cart Source Code Free Download

* Payments are processed with PayPal/Stripe.
* Advanced package also includes the basic package.

$25.00

DownloadDownload

Free Php Shopping Cart Script

For more detailed information on the advanced package click here.

Php Shopping Cart Checkout Code

You have no favorites