Build a Shopping Cart With PHP and MySQL

Where to Find the Best PHP Shopping Cart Scripts for 2021

If you’re looking for a quick, ready-made solution, there are many premium PHP shopping cart scripts to choose from on Envato Market. Here’s a quick look at a few of them.


The best PHP shopping carts are on CodeCanyon.

5 Best PHP Shopping Cart Scripts From CodeCanyon

Before we jump into the shopping cart system PHP tutorial, let’s explore some top PHP shopping cart scripts. If you aren’t an expert at coding, or want to find a ready-to-use solution, these are for you.

1. FleetCart: PHP Shopping Cart + eCommerce System

FleetCart isn’t only a PHP shopping cart. It’s a full eCommerce system for your online store. This powerful PHP shopping cart script has many cool features. It’s fully responsive, multi-language, supports multiple currencies, and more.

With over 1,000 sales and a five-star rating, this is one of our best PHP shopping carts. See how this works in the live preview!

2. LivelyCart: PHP MySQL JQuery Shopping Cart

This is an easy-to-use, customizable PHP MySQL jQuery shopping cart. It’s equipped with two checkout options using PayPal and Submit order by Email. You can use both or either one. It’s a complete PHP shopping cart code download.

3. Digital Paybox: PHP Shopping Cart Script

Digital Paybox is a powerful PHP script which allows you to sell digital products directly on your website. The PHP shopping cart 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 PHP shopping cart code download, you don’t have to install complicated shopping carts and create their design to match your website. This is the easiest way to distribute digital products and monetize a website.

4. Stripe Payment Terminal: PHP Shopping Cart

This PHP shopping cart 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 take less than five minutes (however, you do need to have SSL and a stripe.com account).

5. GeniusCart: PHP Shopping Cart + eCommerce System 

GeniusCart is one of the best PHP shopping carts on CodeCanyon. This PHP MySQL jQuery shopping cart features more than 1,000 sales and a five-star rating.

The PHP shopping cart is a full eCommerce system. You can easily create a single or multivendor store with this solution. You’ve got to check out the preview to watch it in action!

How to Create a Shopping Cart in PHP and MySQL

Here’s a quick video preview on how to build a shopping cart with PHP and MySQL. I’ll go over the full process step by step after this preview. You can watch the full shopping cart system PHP tutorial after the steps.

Step 1

Let’s begin by taking a look at the folder structure:

Structure

reset.css: you can get it reset from this link

style.css: our own CSS file that we will be using to style our HTML markup

connection.php: the file which will do the database connection

index.php: the template for our shopping cart

cart.php: the file where we will able to change our products from the cart (add, remove)

products.php: the products listing page

Step 2

We’ll start by writing the HTML markup and then style it. So open index.php and copy/paste the code below:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<link rel=”stylesheet” href=”css/reset.css” />
<link rel=”stylesheet” href=”css/style.css” />

<title>Shopping cart</title>

</head>

<body>

<div id=”container”>

<div id=”main”>

</div><!–end main–>

<div id=”sidebar”>

</div><!–end sidebar–>

</div><!–end container–>

</body>
</html>

As you can see, our page has two columns: the main column and the sidebar. Let’s move on to the CSS. Open the style.css file and type the code below:

body {
font-family: Verdana;
font-size: 12px;
color: #444;
}

#container {
width: 700px;
margin: 150px auto;
background-color: #eee;
overflow: hidden; /* Set overflow: hidden to clear the floats on #main and #sidebar */
padding: 15px;
}

#main {
width: 490px;
float: left;
}

#sidebar {
width: 200px;
float: left;
}

Here’s how our products page should look now:

Step 3

Before we move on to the PHP/MySQL part, we need to create a 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 that 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:

CREATE TABLE IF NOT EXISTS `products` (
`id_product` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`description` varchar(250) NOT NULL,
`price` decimal(6,2) NOT NULL,
PRIMARY KEY (`id_product`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

INSERT INTO `products` (`id_product`, `name`, `description`, `price`) VALUES
(1, ‘Product 1’, ‘Some random description’, ‘15.00’),
(2, ‘Product 2’, ‘Some random description’, ‘20.00’),
(3, ‘Product 3’, ‘Some random description’, ‘50.00’),
(4, ‘Product 4’, ‘Some random description’, ‘55.00’),
(5, ‘Product 5’, ‘Some random description’, ‘54.00’),
(6, ‘Product 6’, ‘Some random description’, ‘34.00’);

Step 4

Before we move and select 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:

<?php
session_start();
require(“includes/connection.php”);

if(isset($_GET[‘page’])){
$pages=array(“products”, “cart”);

if(in_array($_GET[‘page’], $pages)) {
$_page=$_GET[‘page’];
} else {
$_page=”products”;
}
} else {
$_page=”products”;
}
?>

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 which 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 and 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”. If it’s not, I’m creating a new variable called $_page. If the GET variable called “page” 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 file between the div which has id attribute set to main:

<?php require($_page.”.php”); ?>

Now here’s the complete index.php:

<?php
session_start();
require(“includes/connection.php”);
if(isset($_GET[‘page’])){
$pages=array(“products”, “cart”);

if (in_array($_GET[‘page’], $pages)) {
$_page=$_GET[‘page’];
} else {
$_page=”products”;
}
} else {
$_page=”products”;
}

?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<link rel=”stylesheet” href=”css/reset.css” />
<link rel=”stylesheet” href=”css/style.css” />
<title>Shopping Cart</title>
</head>

<body>
<div id=”container”>
<div id=”main”>
<?php require($_page.”.php”); ?>
</div><!–end of main–>

<div id=”sidebar”>
</div><!–end of sidebar–>
</div><!–end container–>
</body>
</html>

Let’s create the connection to MySQL. Open connections.php and type the following:

<?php
$server=”localhost”;
$user=”tutorial”;
$pass=”supersecretpassword”;
$db=”tutorials”;

$mysqli = new mysqli($server, $user, $pass, $db);

if($mysqli->connect_error) {
die(“Sorry, can’t connect to the mysql.”);
}
?>

Step 5

Now it’s time to write the markup for the products page. So go ahead and open it and type the following:

<h1>Product List</h1>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr>
<td>Product 1</td>
<td>Some random description</td>
<td>15 $</th>
<td><a href=”#”>Add to cart</a></td>
</tr>
<tr>
<td>Product 2</td>
<td>Some random description</td>
<td>25 $</th>
<td><a href=”#”>Add to cart</a></td>
</tr>
</table>

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.

a {color: #48577D; text-decoration: none;}

a:hover {text-decoration: underline;}

h1, h2 {margin-bottom: 15px}

h1 {font-size: 18px;}
h2 {font-size: 16px}
#main table {
width: 480px;
}

#main table th {
padding: 10px;
background-color: #48577D;
color: #fff;
text-align: left;
}

#main table td {
padding: 5px;
}
#main table tr {
background-color: #d3dcf2;
}

Okay: let’s see how it looks now:

Looks a lot better, doesn’t it? Below you have the complete style.css code:

body {
font-family: Verdana;
font-size: 12px;
color: #444;
}

a {color: #48577D; text-decoration: none;}

a:hover {text-decoration: underline;}

h1, h2 {margin-bottom: 15px}

h1 {font-size: 18px;}
h2 {font-size: 16px}

#container {
width: 700px;
margin: 150px auto;
background-color: #eee;
padding:15px;
overflow: hidden;
}

#main {
width: 490px;
float: left;
}

#main table {
width: 480px;
}

#main table th {
padding: 10px;
background-color: #48577D;
color: #fff;
text-align: left;
}

#main table td {
padding: 5px;
}

#main table tr {
background-color: #d3dcf2;
}

#sidebar {
width: 200px;
float: left;
}

Step 6

Before we extract the product from the database, let’s remove the last two table rows from our table (we used them only to see what our table would look like). Remove this:

<tr>
<td>Product 1</td>
<td>Some random description</td>
<td>15 $</th>
<td><a href=”#”>Add to cart</a></td>
</tr>
<tr>
<td>Product 2</td>
<td>Some random description</td>
<td>25 $</th>
<td><a href=”#”>Add to cart</a></td>
</tr>

Great! Now replace the table rows with the following PHP code:

<?php
$sql=”SELECT * FROM products ORDER BY name ASC”;
$result = $mysqli->query($sql);

while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row[‘name’] ?></td>
<td><?php echo $row[‘description’] ?></td>
<td><?php echo $row[‘price’] ?>$</td>
<td><a href=”index.php?page=products&action=add&id=<?php echo $row[‘id_product’] ?>”>Add to cart</a></td>
</tr>
<?php
}
?>

So first we use SELECT to retrieve the products, and then we loop through each row from the database and display 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 link, the product will be 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, the id of the product is passed as a querystring parameter.

Step 7

Let’s make that anchor link work by adding the following code at the top of our page:

<?php
if(isset($_GET[‘action’]) && $_GET[‘action’]==”add”){
$id=intval($_GET[‘id’]);

if(isset($_SESSION[‘cart’][$id])) {
$_SESSION[‘cart’][$id][‘quantity’]++;
} else {
$stmt = $mysqli->prepare(“SELECT * FROM products WHERE id_product = ?”);
$stmt->bind_param(“i”, $id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

if(isset($result[‘id_product’]) && $result[‘id_product’]) {
$_SESSION[‘cart’][$result[‘id_product’]] = array(
“quantity” => 1,
“price” => $result[‘price’]
);
} else {
$message=”This product id is invalid!”;
}
}
}
?>

If the GET variable called action is set and its value is add, we execute the code.
We make sure that the id which is passed through the $_GET variable is an integer.
If the id of the product is already in the $_SESSION variable, we just increment the quantity by one.
If the id is not in the session, we need to make sure that the id which is passed through the $_GET variable exists in the database. If it does, we grab the price and create its session. If it doesn’t, we set a variable called $message which stores the error message.

Let’s check if the $message variable is set and display it on the page (type this code under the H1 page title):

<?php
if(isset($message)) {
echo “<h2>$message</h2>”;
}
?>

Here you can see the complete products.php page.

<?php
if(isset($_GET[‘action’]) && $_GET[‘action’]==”add”) {
$id=intval($_GET[‘id’]);

if(isset($_SESSION[‘cart’][$id])) {
$_SESSION[‘cart’][$id][‘quantity’]++;
} else {
$stmt = $mysqli->prepare(“SELECT * FROM products WHERE id_product = ?”);
$stmt->bind_param(“i”, $id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

if(isset($result[‘id_product’]) && $result[‘id_product’]) {
$_SESSION[‘cart’][$result[‘id_product’]] = array(
“quantity” => 1,
“price” => $result[‘price’]
);
} else {
$message=”This product id is invalid!”;
}
}
}

?>
<h1>Product List</h1>
<?php
if(isset($message)) {
echo “<h2>$message</h2>”;
}
?>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql=”SELECT * FROM products ORDER BY name ASC”;
$result = $mysqli->query($sql);

while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row[‘name’] ?></td>
<td><?php echo $row[‘description’] ?></td>
<td><?php echo $row[‘price’] ?>$</td>
<td><a href=”index.php?page=products&action=add&id=<?php echo $row[‘id_product’] ?>”>Add to cart</a></td>
</tr>
<?php
}
?>
</table>

Here’s the error message if the id of the product is invalid.

Step 8

Let’s go back to the index.php file and build the sidebar. Add the following code:

<h1>Cart</h1>

<?php
if(isset($_SESSION[‘cart’])) {
$arrProductIds=array();

foreach ($_SESSION[‘cart’] as $id => $value) {
$arrProductIds[] = $id;
}
$strIds=implode(“,”, $arrProductIds);

$stmt = $mysqli->prepare(“SELECT * FROM products WHERE id_product IN (?)”);
$stmt->bind_param(“s”, $strIds);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
?>
<p><?php echo $row[‘name’] ?> x <?php echo $_SESSION[‘cart’][$row[‘id_product’]][‘quantity’] ?></p>
<?php
}
?>
<hr />
<a href=”index.php?page=cart”>Go to cart</a>
<?php
} else {
echo “<p>Your Cart is empty. Please add some products.</p>”;
}
?>

Firstly, 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 select all the products from the session and display it.

Take a look at the pictures below:

Since the index.php file is a template for all the files, the sidebar will be visible in the cart.php too. Cool, right?

Step 9

Finally, open cart.php and start by typing the following code:

<h1>View cart</h1>
<a href=”index.php?page=products”>Go back to products page</a>
<form method=”post” action=”index.php?page=cart”>
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Items Price</th>
</tr>
<?php
$arrProductIds=array();
foreach ($_SESSION[‘cart’] as $id => $value) {
$arrProductIds[] = $id;
}
$strIds=implode(“,”, $arrProductIds);

$stmt = $mysqli->prepare(“SELECT * FROM products WHERE id_product IN (?)”);
$stmt->bind_param(“s”, $strIds);
$stmt->execute();
$result = $stmt->get_result();

$totalprice=0;
while ($row = $result->fetch_assoc()) {
$subtotal=$_SESSION[‘cart’][$row[‘id_product’]][‘quantity’]*$row[‘price’];
$totalprice+=$subtotal;
?>
<tr>
<td><?php echo $row[‘name’] ?></td>
<td><input type=”text” name=”quantity[<?php echo $row[‘id_product’] ?>]” size=”5″ value=”<?php echo $_SESSION[‘cart’][$row[‘id_product’]][‘quantity’] ?>” /></td>
<td><?php echo $row[‘price’] ?>$</td>
<td><?php echo $_SESSION[‘cart’][$row[‘id_product’]][‘quantity’]*$row[‘price’] ?>$</td>
</tr>
<?php
}
?>
<tr>
<td colspan=”4″>Total Price: <?php echo $totalprice ?></td>
</tr>
</table>
<br />
<button type=”submit” name=”submit”>Update Cart</button>
</form>
<br />
<p>To remove an item, set it’s quantity to 0. </p>

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 wrapped in a form tag. To get the total price of the items, we multiply the quantity of the specific product (from the session) with its price. This is done in a foreach loop.

NOTE: The input is an array, the key is the id of the product, and the quantity is the quantity value.

Step 10

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.

if(isset($_POST[‘submit’])){

foreach($_POST[‘quantity’] as $key => $val) {
if($val==0) {
unset($_SESSION[‘cart’][$key]);
}else{
$_SESSION[‘cart’][$key][‘quantity’]=$val;
}
}

}

Firstly, 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 than zero, we set the quantity to that value instead.

Here is the complete cart.php file.

<?php
if (isset($_POST[‘submit’])) {
foreach($_POST[‘quantity’] as $key => $val) {
if($val==0) {
unset($_SESSION[‘cart’][$key]);
}else{
$_SESSION[‘cart’][$key][‘quantity’]=$val;
}
}
}
?>

<h1>View cart</h1>
<a href=”index.php?page=products”>Go back to the products page.</a>
<form method=”post” action=”index.php?page=cart”>
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Items Price</th>
</tr>
<?php
$arrProductIds=array();
foreach ($_SESSION[‘cart’] as $id => $value) {
$arrProductIds[] = $id;
}
$strIds=implode(“,”, $arrProductIds);

$stmt = $mysqli->prepare(“SELECT * FROM products WHERE id_product IN (?)”);
$stmt->bind_param(“s”, $strIds);
$stmt->execute();
$result = $stmt->get_result();

$totalprice=0;
while ($row = $result->fetch_assoc()) {
$subtotal=$_SESSION[‘cart’][$row[‘id_product’]][‘quantity’]*$row[‘price’];
$totalprice+=$subtotal;
?>
<tr>
<td><?php echo $row[‘name’] ?></td>
<td><input type=”text” name=”quantity[<?php echo $row[‘id_product’] ?>]” size=”5″ value=”<?php echo $_SESSION[‘cart’][$row[‘id_product’]][‘quantity’] ?>” /></td>
<td><?php echo $row[‘price’] ?>$</td>
<td><?php echo $_SESSION[‘cart’][$row[‘id_product’]][‘quantity’]*$row[‘price’] ?>$</td>
</tr>
<?php
}
?>
<tr>
<td colspan=”4″>Total Price: <?php echo $totalprice ?></td>
</tr>
</table>
<br />
<button type=”submit” name=”submit”>Update Cart</button>
</form>
<br />
<p>To remove an item set its quantity to 0. </p>

I hope that you enjoyed this tutorial. If you have any questions, be sure to watch the more in-depth video tutorial!

Watch How to Create a Shopping Cart in PHP and MySQL

You’ve seen the step-by-step process and the PHP shopping cart sample code. Now, here’s the full video tutorial on how to create a simple shopping cart using PHP & MySQL. 

Discover More PHP Scripts and Resources

I hope you liked the PHP online store tutorial and understand the process of creating a simple shopping cart using PHP and MySQL. If you’d like to explore more useful resources, take a look at this:

PHP
Inventory and Stock Management PHP Scripts
Franc Lucas


PHP
Understanding Variable Scope in PHP
Monty Shokeen


PHP
Formatting the Current Date and Time in PHP
Monty Shokeen


PHP
Example of How to Add Google reCAPTCHA v3 to a PHP Form
Sajal Soni


PHP
How to Make a Live Chat Script in PHP
Sajal Soni


PHP
11 Best PHP Blog Scripts and Blogging Platforms
Franc Lucas


PHP
How to Work With Cookies in PHP
Sajal Soni


PHP
How to Use Sessions and Session Variables in PHP
Sajal Soni

This post has been updated with contributions from Maria Villanueva and Sajal Soni. Maria is a staff writer with Envato Tuts+. Sajal belongs to India, and he loves to spend time creating websites based on open source frameworks.

Generated by Feedzy