Database
Create a new MySQL database named demo and execute the SQL code below:
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 01, 2017 at 01:47 PM
-- Server version: 5.7.14
-- PHP Version: 7.0.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `demo`
--
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`id` int(11) NOT NULL,
`name` varchar(250) NOT NULL,
`datecreation` date NOT NULL,
`status` tinyint(1) NOT NULL,
`username` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `ordersdetail`
--
CREATE TABLE `ordersdetail` (
`productid` int(11) NOT NULL,
`ordersid` int(11) NOT NULL,
`price` decimal(10,0) NOT NULL,
`quantity` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`id` int(11) NOT NULL,
`name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
`price` decimal(10,0) NOT NULL,
`quantity` int(11) NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`id`, `name`, `price`, `quantity`, `description`) VALUES
(1, 'Name 1', '1000', 2, 'good'),
(2, 'Name 2', '2000', 3, 'good'),
(3, 'Name 3', '3000', 4, 'good');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `ordersdetail`
--
ALTER TABLE `ordersdetail`
ADD PRIMARY KEY (`productid`,`ordersid`);
--
-- Indexes for table `product`
--
ALTER TABLE `product`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Database Connection
Create PHP file named connect.php. Use mysqli_connect method connect to demo database with default account:
Username: root
Password:
<?php
$con = mysqli_connect('localhost', 'root', '', 'demo');
?>
List All Products
Create PHP file named index.php. This file will list all products from database as below:
<?php
require 'connect.php';
$result = mysqli_query($con, 'select * from product');
?>
<table cellpadding="2" cellspacing="2" border="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Buy</th>
</tr>
<?php while($product = mysqli_fetch_object($result)) { ?>
<tr>
<td><?php echo $product->id; ?></td>
<td><?php echo $product->name; ?></td>
<td><?php echo $product->price; ?></td>
<td><a href="cart.php?id=<?php echo $product->id; ?>">Order Now</a></td>
</tr>
<?php } ?>
</table>
Item Declaration
Create PHP file named item.php. This class contains information about a product in the cart as below:
<?php
class Item{
var $id;
var $name;
var $price;
var $quantity;
}
?>
Shopping Cart Page
Create PHP file named cart.php. This page lists the products in the shopping cart and allows you to delete and update quantity of items in cart
<?php
session_start ();
require 'connect.php';
require 'item.php';
if (isset ( $_GET ['id'] ) && !isset($_POST['update'])) {
$result = mysqli_query ( $con, 'select * from product where id=' . $_GET ['id'] );
$product = mysqli_fetch_object ( $result );
$item = new Item ();
$item->id = $product->id;
$item->name = $product->name;
$item->price = $product->price;
$item->quantity = 1;
// Check product is existing in cart
$index = - 1;
if (isset ( $_SESSION ['cart'] )) {
$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
for($i = 0; $i < count ( $cart ); $i ++)
if ($cart [$i]->id == $_GET ['id']) {
$index = $i;
break;
}
}
if ($index == - 1)
$_SESSION ['cart'] [] = $item;
else {
$cart [$index]->quantity ++;
$_SESSION ['cart'] = $cart;
}
}
// Delete product in cart
if (isset ( $_GET ['index'] ) && !isset($_POST['update'])) {
$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
unset ( $cart [$_GET ['index']] );
$cart = array_values ( $cart );
$_SESSION ['cart'] = $cart;
}
// Update quantity in cart
if(isset($_POST['update'])) {
$arrQuantity = $_POST['quantity'];
// Check validate quantity
$valid = 1;
for($i=0; $i<count($arrQuantity); $i++)
if(!is_numeric($arrQuantity[$i]) || $arrQuantity[$i] < 1){
$valid = 0;
break;
}
if($valid==1){
$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
for($i = 0; $i < count ( $cart ); $i ++) {
$cart[$i]->quantity = $arrQuantity[$i];
}
$_SESSION ['cart'] = $cart;
}
else
$error = 'Quantity is InValid';
}
?>
<?php echo isset($error) ? $error : ''; ?>
<form method="post">
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Option</th>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Quantity <input type="image" src="http://learningprogramming.net/wp-content/uploads/php-mysql//save.png"> <input
type="hidden" name="update">
</th>
<th>Sub Total</th>
</tr>
<?php
$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
$s = 0;
$index = 0;
for($i = 0; $i < count ( $cart ); $i ++) {
$s += $cart [$i]->price * $cart [$i]->quantity;
?>
<tr>
<td><a href="cart.php?index=<?php echo $index; ?>"
onclick="return confirm('Are you sure?')">Delete</a></td>
<td><?php echo $cart[$i]->id; ?></td>
<td><?php echo $cart[$i]->name; ?></td>
<td><?php echo $cart[$i]->price; ?></td>
<td><input type="text" value="<?php echo $cart[$i]->quantity; ?>"
style="width: 50px;" name="quantity[]"></td>
<td><?php echo $cart[$i]->price * $cart[$i]->quantity; ?></td>
</tr>
<?php
$index ++;
}
?>
<tr>
<td colspan="5" align="right">Sum</td>
<td align="left"><?php echo $s; ?></td>
</tr>
</table>
</form>
<br>
<a href="index.php">Continue Shopping</a>
Checkout Cart
Create PHP file named checkout.php. This fille will store billing information and billing details for a specified account
<?php
session_start ();
require 'connect.php';
require 'item.php';
// Save new order
mysqli_query($con, 'insert into orders(name, datecreation, status, username)
values("New Order", "'.date('Y-m-d').'", 0, "acc2")');
$ordersid = mysqli_insert_id($con);
// Save order details for new order
$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
for($i=0; $i<count($cart); $i++) {
mysqli_query($con, 'insert into ordersdetail(productid, ordersid, price, quantity)
values('.$cart[$i]->id.', '.$ordersid.','.$cart[$i]->price.', '.$cart[$i]->quantity.')');
}
// Clear all products in cart
unset($_SESSION['cart']);
?>
Thanks for buying products. Click <a href="index.php">here</a> to continue buy product.
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Murach’s PHP and MySQL (3rd Edition)
- Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning Php, Mysql, Javascript, Css & Html5)
- PHP and MySQL Web Development (5th Edition) (Developer’s Library)
- Murach’s MySQL, 2nd Edition
- MySQL (5th Edition) (Developer’s Library)
- PHP Ajax Cookbook