Drag and Drop Shopping Cart in PHP-MySQL and JQuery


Create a new MySQL database named mydemo and execute the SQL code below:

-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Apr 23, 2015 at 03:03 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12

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 utf8 */;

--
-- Database: `mydemo`
--

-- --------------------------------------------------------

--
-- Table structure for table `product`
--

CREATE TABLE IF NOT EXISTS `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `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,
  `photo` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `categoryid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `categoryid` (`categoryid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`id`, `name`, `price`, `quantity`, `description`, `photo`, `categoryid`) VALUES
(1, 'Product 1', '1000', 2, 'good', 'thumb1.gif', 1),
(2, 'Product 2', '200', 5, 'good', 'thumb2.gif', 1),
(3, 'Product 3', '500', 8, 'good', 'thumb3.gif', 2),
(4, 'Product 4', '500', 8, 'good', 'thumb1.gif', 3),
(5, 'Product 5', '520', 8, 'good', 'thumb2.gif', 3);

--
-- Constraints for dumped tables
--

--
-- Constraints for table `product`
--
ALTER TABLE `product`
  ADD CONSTRAINT `product_ibfk_1` FOREIGN KEY (`categoryid`) REFERENCES `category` (`id`);

/*!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 */;




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', '', 'mydemo');
?>

Create PHP file named index.php. This page lists the product list and allows users to drag the product into the shopping cart

<?php require 'connect.php'; ?>

<script type="text/javascript"
	src="js/jquery.js"></script>

<script type="text/javascript"
	src="js/jquery-ui-1.8.2.custom.js"></script>

<script type="text/javascript">
	$(document).ready(function() {

		$('#listProducts img').css({
			'z-index' : 100
		}).draggable({
			'opacity' : '0.5',
			'revert' : true,
			'cursor' : 'pointer'
		});

		function displayCart(data) {
            var s = '';
            var sum = 0;
            for (var i = 0; i < data.length; i++) {
                sum += parseInt(data[i].qty) * parseFloat(data[i].price);
                s += '<br><img src="images/' + data[i].photo + '" width="50" height="50">';
                s += '<br>Id: ' + data[i].id;
                s += '<br>Name: ' + data[i].name;
                s += '<br>Quantity: ' + data[i].qty;
                s += '<br>Sub Total: ' + (parseInt(data[i].qty) * parseFloat(data[i].price));
                s += '<br><a href="#?productIdCart=' + i + '" class="delete">Delete</a>';
                s += '<br>--------------------------';
            }
            s += '<br>Totals: ' + sum;
            $('#cart').html(s);
        }

		$('#cart').droppable({
            drop: function (event, ui) {
                var productId = $(ui.draggable).siblings('.productId').val();
                $.ajax({
                    type: 'GET',
                    url: 'cart.php?action=buy&id=' + productId,
                    success: function (data) {
                        displayCart($.parseJSON(data));
                    }
                });
            }
        });

		$('#cart').ajaxComplete(function () {
            $('.delete').bind('click', function () {
                var productIdCart = $(this).attr('href').split('=');
                $.ajax({
                    type: 'GET',
                    url: 'cart.php?action=delete&index=' + productIdCart[1],
                    success: function (data) {
                    	displayCart($.parseJSON(data));
                    }
                });
            });
        });

	});
</script>

<div style="float: left; margin-right: 10px;" id="listProducts">
	<table cellpadding="2" cellspacing="2" border="1">
		<tr>
			<th>Id</th>
			<th>Name</th>
			<th>Price</th>
			<th>Photo</th>
		</tr>
		<?php
			$result = mysqli_query($con, 'select * from product');
			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><img
				src="images/<?php echo $product->photo; ?>"
				width="120" height="100" class="productPhoto" />
				<input
				type="hidden" class="productId" value="<?php echo $product->id; ?>" /></td>
		</tr>
		<?php } ?>
	</table>
</div>

<div id="cart"
	style="width: 200px; min-height: 200px; border: 1px solid red; margin-left: 300px; padding: 5px;">

</div>




Create PHP file named item.php. This class contains information about a product in the cart

<?php
class Item {
	var $id;
	var $name;
	var $price;
	var $qty;
	var $photo;
}
?>

Create PHP file named cart.php. This page lists the products in the shopping cart and allows you to delete the selected product

<?php
session_start ();
require 'connect.php';
require 'item.php';
if ($_GET ['action'] == 'buy') {
	if (isset ( $_GET ['id'] )) {
		$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->qty = 1;
		$item->photo = $product->photo;
		$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;
			$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
		} else {
			$cart [$index]->qty ++;
			$_SESSION ['cart'] = $cart;
			$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
		}
		echo json_encode ( $cart );
	}
} else if ($_GET ['action'] == 'delete') {
	if (isset ( $_GET ['index'] )) {
		$cart = unserialize ( serialize ( $_SESSION ['cart'] ) );
		unset ( $cart [$_GET ['index']] );
		$cart = array_values ( $cart );
		$_SESSION ['cart'] = $cart;
		echo json_encode ( $cart );
	}
}
?>

I recommend you refer to the books below to learn more about the knowledge in this article: