How to design Simple shopping cart in PHP

This example can help you to build a simple shopping cart. In this example i am using PHP, MySql and PHP SESSION to complete In this example. In this tutorial we are diplaying the products from database, storing the products using session in cart section and removing the products from cart section. This example is very useful if you know basic coding of php and MySql.

Now i am going to display the output of Products Page and Cart Page of this shoping cart.

Product Page Output:

simple shopping cart page

PHP Shopping Cart Files:

Here is the files overview can help you keep track of which files we are using for this tutorials. Here's the overview of the files used in this tutorial.

shoping cart file structure

Implementation of code:

shop.sql: Import this file in database to create product table in shop database . Or you can create manually product table in shop datebase. Here is the code of this file.

MySql Script to create Emplyee Table:

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

CREATE TABLE IF NOT EXISTS `product` (
  `sr` int(11) NOT NULL AUTO_INCREMENT,
  `productID` int(11) NOT NULL,
  `productName` text NOT NULL,
  `price` varchar(100) NOT NULL,
  PRIMARY KEY (`sr`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

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

INSERT INTO `product` (`sr`, `productID`, `productName`, `price`) VALUES
(1, 1, 'LG P880 4X HD', '1000'),
(2, 2, 'Google Nexus 4', '2000'),
(3, 3, 'Samsung Galaxy S4', '4000'),
(4, 4, 'Sony XPERIA', '6000');

config.php: This file is used to create a connection to the database to access data from database.

config.php:

This file is used to create a connection to the database to access data from database.

<?php

$con = mysqli_connect("localhost", "root", "","shop");

?>

index.php

This file is used to display products from database.

<?php

session_start();

include_once('config.php');

$itemCount = 0;

if(isset($_SESSION['cart'])){
   
$itemCount = count(isset($_SESSION['cart']) ? $_SESSION['cart'] : array());

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" href="css/css.css" type="text/css" />

<title>Simple Shoping Cart in php</title>

</head>

<body>

<div class="hdr"><img src="https://coderglass.com/images/logo.png"/></div>

<h2 class="hlab">Simple shopping CART system!!</h2>

    <nav>
	<div class="nav-bar">
	<ul>
	<li><a href="index.php">Home</a></li>
	<li><a href="cart.php">View Cart</a></li>
	<li><div class="cart-a">{ <?php echo $itemCount; ?> }
        </div></li>   
         </ul>
         <div class="clear"></div>
        </div>
    </nav>

	<div class="container main-cude">
        <p class="msg">

        <?php if(isset($_REQUEST['msg'])){

			switch($_REQUEST['msg']):

			case 'add':

            $msg = $_REQUEST['p'] . " was added to your cart.";

            break;

            case 'exists':

            $msg = $_GET['p'] . " already in your cart.";

            break;

            endswitch;

            echo $msg;

            }

        ?>

        </p>

    <h2>Products in shop</h2>

        <ul class="item-cont">
         <li>Product Name</li>
         <li>Price</li>
         </ul>

    <div class="clear"></div>

        <?php

	$qur = mysqli_query($con,"SELECT * FROM  `product` ");

        while($r = mysqli_fetch_array($qur)){

        extract($r);
        ?>
   
    <div>
    <div class="inline-pr"><?=$productName?></div>
    <div class="inline-pr"><?=$price?></div>
    <div class="inline-pr">
    <a href="curd.php?action=add&pid=<?=$productID?>&p=<?=$productName?>" 
	class="button-cart">Add to Cart</a>
    </div>
    </div>
    <?php }?>

    <div class="clear"></div>
</div>
</body>
</html>

curd.php:

This file is used to check product was already added or remove from session.

<?php
  
  session_start();

	if(!isset($_REQUEST['pid'])){
		
		exit();
    }
 
    $pid = $_REQUEST['pid'];
	
	$pname = $_REQUEST['p'];

	$case = $_REQUEST['action'];


    // Check if session varible is set or not
	
	if(!isset($_SESSION['cart'])){

        $_SESSION['cart'] = array();

        }

    switch($case):

    case 'add':

        // Now check if product is already stored in session variable

    if(in_array($pid, $_SESSION['cart'])){

       // redirect to product list and tell the user it was added to cart

    header('Location: index.php?msg=exists&id=' . $pid . '&p=' . $pname);

    }

    else{

        if(!preg_match('/^[0-9]{1,}$/i', $pid)){

            header('Location: index.php?msg=exists&id' . $pid . '&p=' . $pname);

        }else{

             array_push($_SESSION['cart'], $pid);        

              // redirect to product list and tell user it was added to cart


            header('Location: index.php?msg=add&id' . $pid . '&p=' . $pname);

            }

        }
    break;

case 'remove':

	if(!preg_match('/^[0-9]{1,}$/i', $pid)){

		header('Location: index.php?msg=exists&id' . $pid . '&p=' . $pname);

        }else{

             $_SESSION['cart'] = array_diff($_SESSION['cart'], array($pid));

               // redirect to product list and tell the user it was removed from cart

             header('Location: cart.php?msg=removed&id=' . $id . '&p=' . $pname);


                              }
break;

endswitch;
?>