
Shopping Cart Example PHP
There are many e-commerce application and we are still building e-commerce application but all of them has common functionality and the functionality is shopping cart.
We are here to learn, How to build a simple shopping cart in PHP and MySQL? In this article I'll be creating a very simple cart system where you will be able to add the products into the cart and can remove the products from the cart. You also will be able to empty cart or remove all products from the cart.
Here are the MySQL queries:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
create database cart;
use cart;
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`product_title` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`price` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
ALTER TABLE `products`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
INSERT INTO `products` (`id`, `product_title`, `image`, `price`) VALUES
(1, 'Shoes', 'shoes.jpeg', 2399),
(2, 'Shirt', 'shirt.jpeg', 1199),
(3, 'Watch', 'watch.jpeg', 1299),
(4, 'Bag', 'bag.jpeg', 1200);
|
I'll be using session to add or remove the products from the cart. First of all I'm fetching products from MySQL and listing all the products on the web page.
Create a new PHP file like:
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?php
session_start();
include_once 'connection.php';
include_once 'product-action.php';
include_once 'cart.php';
$stmt = $conn->prepare("SELECT * FROM products ORDER BY id ASC");
$stmt->execute();
$products = $stmt->get_result();
echo '<table style="border: 1px solid #ddd;"><tr>';
if (!empty($products)) {
foreach($products as $product){
?>
<td style="border: 1px solid #ddd;">
<form method="post" action="index.php?action=add&id=<?php echo $product['id']; ?>">
<div class="product-image"><img src="images/<?php echo $product['image']; ?>" width="200" height="200"></div>
<div><strong><?php echo $product["product_title"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product["price"]; ?></div>
<div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" /></div>
</form>
</td>
<?php }}
echo '</tr></table>';
|
Here is the simple products listing. I also have add to cart button here and a text field to enter the quantity. I also have used connection file here which creates a connection with MySQL using PHP. ...