PHP MySQL E-Commerce Shopping Cart Scripts

Building a PHP shopping cart simple ecommerce shopping cart php mysql is simple and easy. As I will cover this Post with live Working example to develop Simple PHP Shopping Cart, so the some major files and add to cart in php Directory File Structure for this example is following below.let’s make a simple OOP PHP shopping cart web Application with MySQL

Simple Shopping Cart with PHP

There are the following step by step Simple shopping Cart Application using PHP

  • Import simple database “mysql_import.sql” in your MySql login to PhpMyAdmin to create “item” table.
  • Change simple settings in database connection “config.php” for your database.
  • Navigate to simple default index page of your simple shopping cart and Good Luck.

Examples of php shopping cart

Simple Ecommerce PHP Shopping Cart Application
Simple Ecommerce PHP Shopping Cart Application

simple shopping cart File list

  • index.php
  • dbcontroller.php
  • style.css

Step 1: Database Product Table for Shopping Cart

simple ecommerce shopping cart php mysql for shop_products_table TABLE

--
-- Table structure for table `shop_products_table`
--

CREATE TABLE `shop_products_table` (
  `id` int(8) NOT NULL,
  `name` varchar(255) NOT NULL,
  `code` varchar(255) NOT NULL,
  `image` text NOT NULL,
  `price` double(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `shop_products_table`
--

INSERT INTO `shop_products_table` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'Intex 58431 Soft Side Zwembad 188x46 cm', '3DcAM01', 'product-images/camera.jpg', 25000.00),
(2, 'Sluban M38-B0587E Army Artillery', 'USB02', 'product-images/external-hard-drive.jpg', 26852.00),
(3, 'Sluban M38-B0587D Army Mine Clearer', 'wristWear03', 'product-images/watch.jpg', 24785.00),
(4, 'Snor Smart Bed', 'LPN45', 'product-images/laptop.jpg', 85475.00);

--
-- Indexes for table `shop_products_table`
--
ALTER TABLE `shop_products_table`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `product_code` (`code`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `shop_products_table`
--
ALTER TABLE `shop_products_table`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;

PHP Shopping Cart Software Development

index.php
This is where I will make a simple HTML form and PHP server side source code for our web application. To make the forms simply all souce code copy and write it into your any text editor Like Notepad++, then save file it as index.php.

<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
	case "add":
		if(!empty($_POST["quantity"])) {
			$productByCode = $db_handle->runQuery("SELECT * FROM shop_products_table WHERE code='" . $_GET["code"] . "'");
			$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));
			
			if(!empty($_SESSION["add_to_cart_products"])) {
				if(in_array($productByCode[0]["code"],array_keys($_SESSION["add_to_cart_products"]))) {
					foreach($_SESSION["add_to_cart_products"] as $k => $v) {
							if($productByCode[0]["code"] == $k) {
								if(empty($_SESSION["add_to_cart_products"][$k]["quantity"])) {
									$_SESSION["add_to_cart_products"][$k]["quantity"] = 0;
								}
								$_SESSION["add_to_cart_products"][$k]["quantity"] += $_POST["quantity"];
							}
					}
				} else {
					$_SESSION["add_to_cart_products"] = array_merge($_SESSION["add_to_cart_products"],$itemArray);
				}
			} else {
				$_SESSION["add_to_cart_products"] = $itemArray;
			}
		}
	break;
	case "remove":
		if(!empty($_SESSION["add_to_cart_products"])) {
			foreach($_SESSION["add_to_cart_products"] as $k => $v) {
					if($_GET["code"] == $k)
						unset($_SESSION["add_to_cart_products"][$k]);				
					if(empty($_SESSION["add_to_cart_products"]))
						unset($_SESSION["add_to_cart_products"]);
			}
		}
	break;
	case "empty":
		unset($_SESSION["add_to_cart_products"]);
	break;	
}
}
?>
<HTML>
<HEAD>
<TITLE>Simple PHP Shopping Cart</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart</div>

<a id="btnEmpty" href="index.php?action=empty">Empty Cart</a>
<?php
if(isset($_SESSION["add_to_cart_products"])){
    $total_quantity = 0;
    $total_price = 0;
?>	
<table class="tbl-cart" cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th style="text-align:left;">Product Name</th>
<th style="text-align:left;">Product Code</th>
<th style="text-align:right;" width="5%">Product Quantity</th>
<th style="text-align:right;" width="10%">Product Unit Price</th>
<th style="text-align:right;" width="10%">Product Price</th>
<th style="text-align:center;" width="5%">Remove</th>
</tr>	
<?php		
    foreach ($_SESSION["add_to_cart_products"] as $item){
        $item_price = $item["quantity"]*$item["price"];
		?>
				<tr>
				<td><img src="<?php echo $item["image"]; ?>" class="cart-item-image" /><?php echo $item["name"]; ?></td>
				<td><?php echo $item["code"]; ?></td>
				<td style="text-align:right;"><?php echo $item["quantity"]; ?></td>
				<td style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td>
				<td style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td>
				<td style="text-align:center;"><a href="index.php?action=remove&code=<?php echo $item["code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td>
				</tr>
				<?php
				$total_quantity += $item["quantity"];
				$total_price += ($item["price"]*$item["quantity"]);
		}
		?>

<tr>
<td colspan="2" align="right">Total:</td>
<td align="right"><?php echo $total_quantity; ?></td>
<td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td>
<td></td>
</tr>
</tbody>
</table>		
  <?php
} else {
?>
<div class="no-records">Your Cart is Empty</div>
<?php 
}
?>
</div>

<div id="product-grid">
	<div class="txt-heading">Products List</div>
	<?php
	$product_array = $db_handle->runQuery("SELECT * FROM shop_products_table ORDER BY id ASC");
	if (!empty($product_array)) { 
		foreach($product_array as $key=>$value){
	?>
		<div class="product-item">
			<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
			<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
			<div class="product-tile-footer">
			<div class="product-title"><?php echo $product_array[$key]["name"]; ?></div>
			<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
			<div class="cart-action"><input type="text" class="product-quantity" name="quantity" value="1" size="2" /><input type="submit" value="Add to Cart" class="btnAddAction" /></div>
			</div>
			</form>
		</div>
	<?php
		}
	}
	?>
</div>
</BODY>
</HTML>

dbcontroller.php

<?php
class DBController {
	private $host = "localhost";
	private $user = "root";
	private $password = "";
	private $database = "blog_samples";
	private $conn;
	
	function __construct() {
		$this->conn = $this->connectDB();
	}
	
	function connectDB() {
		$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
		return $conn;
	}
	
	function runQuery($query) {
		$result = mysqli_query($this->conn,$query);
		while($row=mysqli_fetch_assoc($result)) {
			$resultset[] = $row;
		}		
		if(!empty($resultset))
			return $resultset;
	}
	
	function numRows($query) {
		$result  = mysqli_query($this->conn,$query);
		$rowcount = mysqli_num_rows($result);
		return $rowcount;	
	}
}
?>

Also Read: php shopping chart

PHP E-Commerce Shopping Cart Application step by step
PHP E-Commerce Shopping Cart Application step by step

CSS Code
body {
	font-family: Arial;
	color: #211a1a;
	font-size: 0.9em;
}

#shopping-cart {
	margin: 40px;
}

#product-grid {
	margin: 40px;
}

#shopping-cart table {
	width: 100%;
	background-color: #F0F0F0;
}

#shopping-cart table td {
	background-color: #FFFFFF;
}

.txt-heading {
	color: #211a1a;
	border-bottom: 1px solid #E0E0E0;
	overflow: auto;
}

#btnEmpty {
	background-color: #ffffff;
	border: #d00000 1px solid;
	padding: 5px 10px;
	color: #d00000;
	float: right;
	text-decoration: none;
	border-radius: 3px;
	margin: 10px 0px;
}

.btnAddAction {
    padding: 5px 10px;
    margin-left: 5px;
    background-color: #efefef;
    border: #E0E0E0 1px solid;
    color: #211a1a;
    float: right;
    text-decoration: none;
    border-radius: 3px;
    cursor: pointer;
}

#product-grid .txt-heading {
	margin-bottom: 18px;
}

.product-item {
	float: left;
	background: #ffffff;
	margin: 30px 30px 0px 0px;
	border: #E0E0E0 1px solid;
}

.product-image {
	height: 155px;
	width: 250px;
	background-color: #FFF;
}

.clear-float {
	clear: both;
}

.demo-input-box {
	border-radius: 2px;
	border: #CCC 1px solid;
	padding: 2px 1px;
}

.tbl-cart {
	font-size: 0.9em;
}

.tbl-cart th {
	font-weight: normal;
}

.product-title {
	margin-bottom: 20px;
}

.product-price {
	float:left;
}

.cart-action {
	float: right;
}

.product-quantity {
    padding: 5px 10px;
    border-radius: 3px;
    border: #E0E0E0 1px solid;
}

.product-tile-footer {
    padding: 15px 15px 0px 15px;
    overflow: auto;
}

.cart-item-image {
	width: 30px;
    height: 30px;
    border-radius: 50%;
    border: #E0E0E0 1px solid;
    padding: 5px;
    vertical-align: middle;
    margin-right: 15px;
}
.no-records {
	text-align: center;
	clear: both;
	margin: 38px 0px;
}

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about php shopping cart.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Laravel 5.7 JQuery AJAX Tutorial Example
  2.   Generate PDF in Laravel 5.8 example
  3.   PHP Remove File from Folder and Database
  4.   Add Session Array programming with php
  5.   WooCommerce Get Product Downloads
  6.   Laravel PHP Artisan Commands list with Example
  7.   php array remove keys keep values
  8.   Laravel Calculate Age from Date of Birth in MySQL
  9.   Send Emails Using Laravel 6 Mailable Class?
  10.   How to convert base64 to image and save in folder php?