How to build a shopping cart in php and mysql?
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. Show
We'll be using the PDO interface to access our MySQL database with PHP as it will make it much easier for us to interact with our database and manipulate our tables. 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. 1. Getting StartedThere 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. DemosBelow 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
1.3. What You Will Learn in this Tutorial
1.4. File Structure & SetupWe can now start our web server and create the files and directories we're going to use for our shopping cart system.
File Structure \-- shoppingcart Each file/directory will contain the following:
2. Creating the Database and setting-up TablesFor 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:
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:
On phpMyAdmin this should look like: http://localhost/phpmyadmin/ The above SQL statement code will create the products table with the following columns:
The SQL statement will also insert 4 example products that we can use for testing purposes. You can change/remove them later on in the tutorial when we've implemented the code. 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:
This will be the stylesheet we'll use for the shopping cart system. 4. Creating the Functions FileThe functions.php file will contain all the functions we're going to use in our shopping cart system which 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 template 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 FileThe index.php file will basically be our main file for accessing all our pages. We'll set-up basic routing and use GET requests to determine which page is which. 5.1. Connect to MySQL DatabaseEdit the index.php file and add the following:
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 RoutingAdd 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 PageThe 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 DatabaseEdit the home.php file and add the following:
The above code will execute a SQL query that will retrieve the four most recently added products from our database. 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 TemplateAdd 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: http://localhost/shoppingcart/index.php 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 PageThe 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. Edit the products.php file and add the following:
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 ProductsAdd 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 TemplateAdd after the PHP closing tag:
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 PageThe 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 RequestEdit 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 TemplateAdd after the PHP closing tag:
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 PageThe 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 CartEdit 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 CartAdd after:
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 QuantitiesAdd 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 OrderAdd after:
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 DatabaseAdd 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 TemplateAdd below the PHP closing tag:
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: http://localhost/shoppingcart/index.php?page=cart 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:
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 PageThis 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. 10.1. Creating the Place Order TemplateEdit the placeorder.php file and add the following:
And now if we add a product to our shopping cart and click the Place Order button, we'll see the following: http://localhost/index.php?page=placeorder Feel free to change the place order message, etc. ConclusionCongratulations! You've successfully created a shopping cart system with PHP and MySQL! What next? Consider implementing a checkout page and integrate a payment method, such as PayPal. PayPal provide their own API for developers, which you can leverage. In addition, 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 deploying the system for production until you have made a reasonable amount of changes and additions. I'd suggest you 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 as it will help us create more future content. If you would like to support us, consider purchasing the advanced package below. Your support will greatly help us create more tutorials and keep our server up and running. BasicAdvancedSource code Database SQL file Shopping cart page Product & Products page Place order page Checkout page My account page Update quantity feature Account creation feature Transactions feature PayPal integration Stripe integration Coinbase Commerce integration Admin panel Order details email feature Product options feature Product categories feature Product images feature Product shipping feature Product discounts feature Digital downloads Search products feature Sort products feature Empty cart feature Interactive upload media manager Responsive design (mobile friendly) SCSS file Commented code Free updates & support User Guide * Payments are processed with PayPal/Stripe. For more detailed information regarding the advanced package, click here. How do I make a shopping cart database?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.
How add to cart works in PHP?They are add-to-cart, remove a single item from the cart, clear the complete cart and similar. In the above code, I have added the HTML option to add the product to the shopping cart from the product gallery. When the user clicks the 'Add to Cart' button, the HTML form passes the product id to the backend PHP script.
How shopping cart can be maintained with session concept sample PHP code?Cart Library (Cart.class.php)
get_item() – Returns a specific cart item details. total_items() – Returns the total item count in cart. total() – Returns the total price of the cart. insert() – Insert items into the cart and save them in the SESSION.
|