Shoppingcart using PHP Sessions - Miniproject

Shoppingcart using PHP Sessions - Miniproject


Shopping cart using PHP Sessions, MySQL


In this tutorial, you are going to learn how to build a simple shopping cart project using PHP and MySQL. It is a basic project aimed for beginners.

This project uses PHP Session to implement shopping cart. Within the session, a cart is created. Sessions allows you managing the products in the cart. Such as…

  • adding product to the cart, 
  • modifying the product quantity, 
  • deleting the product
  • finding the total number of products in the cart. etc.

  Download source code from the given link:

Note: Scan the code with antivirus and use it.

Download

Here are steps to accomplish the project. Just follow them.

STEP-1  

Create a project in a server.

Create an image's folder inside the project folder. As given in the picture. Copy some sample products images in that.


GO TOP↑

 

STEP-2:

Start server.

Open PhpMyAdmin tool in a browser,

Create a database, with name shoppingcartdb.

Create Table. And insert Data using the given queries.

 Queries:

 

--
-- Database: `shoppingcart`
--

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

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `price` float NOT NULL,
  `image` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `price`, `image`) VALUES
(1, 'PRODUCT A', 100, 'p1.png'),
(2, 'PRODUCT B', 200, 'p2.png'),
(3, 'PRODUCT C', 300, 'p3.png');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;

 

STEP-3:

Create all the given PHP files in project folder one by one.

  1. config.php

  2. shop.php

  3. cart.php

  4. viewcart.php

  5. empty_cart.php

 

MOVETOP↑

 

 config.php

  This file contains database connection details.

 <?php

$databaseHost = 'localhost';
$databaseName = 'shoppingcartdb';
$databaseUserName = 'root';
$databasePassword = '';

$conn = mysqli_connect($databaseHost, $databaseUserName, $databasePassword, $databaseName); 

// Test connection
if (mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


?> 

shop.php

Displays a list of products. Using 'Add to Cart' link, user add the product to cart. 
When user select the product automatically product-id and quantity are sent to cart.php.
 
<!DOCTYPE html>
<html>
<head>
    <title>Coding-zon PHP Shopping Cart Demo</title>
</head>
<body>

<?php
session_start(); 
?> 
 
***************PRODUCT LIST******************* 
 <h2> SHOP HERE</h2>
<div>
product A
<a href="cart.php?id=1&qty=1">Add to cart </a>
</div>

<div>
product B
<a href="cart.php?id=2&qty=1">Add to cart </a>
</div>

<div>
product C
<a href="cart.php?id=3&qty=1">Add to cart </a>
</div>


</body>
</html>
 
 output:
 
 

 
 

 TOP

 
 
 

cart.php  

 

Adds the products to the cart. And provides a link to view cart items.

 

<?php
session_start();

 
if(!(isset($_SESSION['cart']))){
$_SESSION['cart']=array();
} 

 
if(empty($_SESSION['cart'])){
$_SESSION['cart'] = array();
}

 if(isset($_GET['id']))
{
$pid = $_GET['id'];
$qty = $_GET['qty'];
} 
 
***************PRODUCT ADDED TO CART ******************* 
 
 if(!(in_array($pid,$_SESSION['cart']))){
 
$_SESSION['cart'][$pid] = $qty; 
}
 
?>
<h2>

<BR><a href="show_cart.php">view cart </a>
</h2>
 
 

GOTOP↑

 

show_cart.php

 Displays the products from cart array. Calculates subtotal and grand total. It also allows changing the quantity of the products. Provides the links to shop more and also to empty the cart.

<?php
session_start(); 
$qtyval=0;
//print_r($_SESSION['cart']);

if(empty($_SESSION['cart']))
  die('No Products in the Cart<br> <a href="shop.php">Go to SHOP </a>');
 
//extracts all products keys from the cart
 
$idsarray = array_keys($_SESSION['cart']);
  $ids = implode(',', array_keys($_SESSION['cart']));

include("config.php");
 
$sql = "SELECT * FROM products WHERE id IN($ids)";

$res = mysqli_query($conn,$sql);
echo "<br>".$sql;


echo "<br>Your Cart Items are  = ".$ids;

echo "<br>Total   Items are  = ". count($idsarray);
echo "<h2> Products Details of the Cart ids <br> Qty can be modified.[ 0 - for delete product]</h2>";
echo "<h4>  Products in the cart </h4>";
echo "<table border='1' bgcolor='pink'> <tr> <td>ID</td> <td>PRODUCT IMAGE</td><td>PRODUCT NAME</td><td>PRICE</td><td>QTY</td><td>SUB</td></tr>";
$gtotal=0;
$qty=0;

if(isset($_GET['cpid'])){   // to modify qty 
	
$pid=$_GET['cpid'];    // modified product id
$qty=$_GET['cqty'];    // modified product qty

//echo " qty and id = ".$_GET['cpid'].$_GET['cqty']."<br>";
if($qty > 0 and (filter_var($qty, FILTER_VALIDATE_INT)!== false))
	{
	foreach($idsarray as $id ){ 
		//$k = $_SESSION['cart'][$id];
		if($id == $pid)
		 {
		$_SESSION['cart'][$pid] = $qty;
		}	
		 
 else if($qty == 0)
		 {
		 unset($_SESSION['cart'][$pid]);
		 header("Location:show_cart.php");
		 }
else
{
echo "bad input";  // when non numeric value entered
}
}

	$sub=0;
	$qtyval ;
	 while($productdetails = mysqli_fetch_assoc($res)){
	
		echo "<tr>";
		echo "<td>" .$productdetails['id']. "</td>";
		echo '<td><img src= "images/' .$productdetails['image']. '" height="100" width="100"></td>';
		echo "<td>" .$productdetails['name']. "</td>";
		echo "<td>" .$productdetails['price']."</td>";
		$id = $productdetails['id'];
	    $qtyval = $_SESSION['cart'][$id]; 
		// modifying quantity
			echo '<td><form action="" method="get">'.
			'<input type="hidden" name="cpid"  value="' .$productdetails['id'].'">'.
			'<input type="number" value="' .$qtyval.'" name="cqty" >'.
		 '<input type="submit" name="submit" value="go"></form></td>';
	
		 $sub = $qtyval*$productdetails['price'];
	 $gtotal+=  $sub;
		echo '<td>'.$sub.'</td>';
		echo "</tr>";
 }
echo "</table>";
echo "<br> Grand total : ". $gtotal;

echo "<br>";


?>

<a href="empty_cart.php?">Empty cart </a>

<br> 
<div>
Want to shop more?
<br><a href="shop.php">Go to SHOP </a>
</div> 

 

TOP↑

 

empty_cart.php

Clears all the cart items and empties the cart. Provides a link to shop again.

 

<?php

session_start();
$_SESSION['cart'] = array();
echo "<br>Cart emptied <br>";
?>

<br>
<div>
Shop Again?
<br><a href="shop.php">Go to SHOP </a>
</div>

STEP-4:

  • Start the server.
  • Open shop.php in the browser and run it and add products. 
  • you will see the result as shown in below given image.


 
 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP