How to design Simple shopping cart in PHP for beginners.

POSTED

AUTHOR: VARUN SINGH

In this tutorial todays i am going to explain a simple PHP example for creating shopping cart website. 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:

Here is the output of the Products Page. You can add products from here to cart section.

php-shoping-cart

Cart Page Output:

Here is the output of the Cart Page. You can remove products from here.

php-shoping-cart

PHP Shopping Cart Tutorial 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.

php-shoping-cart

Implementation of code:

php-tips Fist you will have to create database with name shop.


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.

--
-- 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.

<?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>


<div class="resv">
	<a href="http://coderglass.com"> coderglass.com</a>
	<a href="http://coderglass.com" style="float:right">Powered By:- Coder Glass</a>
</div>

</body>
</html>


cart.php: This file is used to add or remove product prom session.

<?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" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://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="http://coderglass.com/images/logo.png"/></div>


<h2 class="hlab">Simple shopping cart in php</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><a href="#">Checkout</a></li>
               <li><div class="cart-a">{ <?=$itemCount?> }</div></li>   

        </ul>


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


  </div>


</nav>


			<div class="container main-cude">

				<p class="msg">

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

					$msg ="";

					switch($_REQUEST['msg']):

					case 'add':


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


                    break;


                    case 'exists':


                    $msg = '<b>'.$_GET['p'] . "</b> already in your cart.";


                    break;


                    case 'removed':


                    $msg = '<b>'.$_GET['p'] . "</b> was removed from your cart.";


                    break;


                    endswitch;


                    echo $msg;


                     }


                ?>

            </p>


    <?php

    // If cart is empty and user click on cart button show default product list

    if($itemCount == 0){

    echo '<b>Your Cart is empty!.';

    echo ' Add items to it. </b>';

    ?>

    <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 }

       }

    // If user add product to its cart

    else{?>

        <h2>Products in your CART</h2>

        <?php

			$pids = "";

			foreach($_SESSION['cart'] as $id){

			$pids = $pids. $id.',';

            }


                        $pids = rtrim($pids, ",");

						$sql = "SELECT productID, productName, price FROM product WHERE productID IN (".$pids.")";

						$qur = mysqli_query($con,$sql);

						$row = mysqli_num_rows($qur);  // Count num of rows

						if($row == 0){

					         echo '<p class="msg">No products found in your cart.</p>';

						}else{

                        ?>

        <ul class="item-cont">

				<li>Product Name</li>
				<li>Price</li>

		</ul>

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

        <?php

            $totalPrice = '';

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

			extract($res);

			$totalPrice += $price;

        ?>


            <div>


                <div class="inline-pr"><?=$productName?></div>

                <div class="inline-pr"><?=$price?></div>

                <div class="inline-pr"><a href="curd.php?action=remove&pid=<?=$productID?>&p=<?=$productName?>" class="button-cart red-bt">Remove</a></div>


            </div>


        <?php } ?>


            <div style="margin-top: 20px; border-top: #999 solid 1px;">


                <div class="inline-pr"><b>Total</b></div>

				<div class="inline-pr" style="font-weight: bold;">RS. <?=$totalPrice?></div>

				<div class="inline-pr">&nbsp;</div>


            </div>


        <?php } } ?>


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


</div>


<div class="resv">

    <a href="http://www.coderglass.com/">&copy; Coder Glass</a>

    <a href="http://www.coderglass.com/" style="float:right">
     Powered By:- Coder Glass</a>

</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;
?>

download download

The End:

Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section. We will be very happy to hear that.

If you like my tutorial, please follow us on facebook, Google + and Twitter. I need your support to continue.


Comments: