PHP Shopping Cart - Web Development and Web Design Codes

Latest

Thursday, February 15, 2018

PHP Shopping Cart

PHP Shopping Cart

PHP Shopping Cart
PHP Shopping Cart
Hi Friends Today we are going to learn how to create php shopping cart using session..in this example you will learn how to add items into cart,display items from cart and remove items from cart using php session..
learn more about PHP SESSION

Learn PHP Add to cart
Copy and try The below Codes:
1. index.php
<?php
session_start();
//Define Product name and Price
$product=array("ASUS Vivobook","PHP Probook","Nokia Lumia 1020","Sony XA Ultra");
$price=array("653","416","718","350");
?>
<?php
//If the session does not exist
if(!isset($_SESSION["total"])){
 $_SESSION['total']=0;
 for($i=0;$i<count($product);$i++){
  $_SESSION['qty'][$i]=0;
  $_SESSION['price'][$i]=0;
 }
}
//adding product to cart
if(isset($_GET['add'])){
 $i=$_GET['add'];
 $qty=$_SESSION['qty'][$i]+1;
 $_SESSION['price'][$i]=$price[$i] * $qty;
 $_SESSION['cart'][$i]=$i;
 $_SESSION['qty'][$i]=$qty;
 //After Adding Product To cart we send User Index page
 header('location:index.php');
}
//Remove Product From Cart
if(isset($_GET['remove'])){
 $pid=$_GET['remove'];
 unset($_SESSION['cart'][$pid]);
 //Setting Quantity 0 for Removed Product
 $_SESSION['qty'][$pid]=0;
}
?>
<h2>PHP Shopping Cart</h2>
 <table cellspacing="0" border="1">
    <tr>
    <th>Product</th>
    <th>Price</th>
    <th>Action</th>
 </tr>
 <?php
for($i=0;$i<count($product);$i++){?>
 <tr>
    <td><?php echo $product[$i];?></td>
    <td>$<?php echo $price[$i];?></td>
    <td><a href="?add=<?php echo $i;?>">Add Cart</a></td>
 </tr>
 <?php
 };
?>
 </table>
 <?php
 if(!empty($_SESSION['cart']))
 {?>
 <h2> Your Cart</h2>
 <table cellspacing="0" border="1">
    <tr>
    <th>Product</th>
    <th>Price</th>
    <th>Quantity</th>
    <th>Action</th>
 </tr>
 <?php 
 $total=0;
  foreach($_SESSION['cart']as $i){?>
 <tr>
    <td><?php echo $product[$_SESSION['cart'][$i]];?></td>
    <td>$<?php echo $_SESSION['price'][$i];?></td>
    <td><?php echo $_SESSION['qty'][$i];?></td>
    <td><a href="?remove=<?php echo $i;?>">Remove</a></td>
 </tr>
 
 <?php 
$total+=$_SESSION['price'][$i];
 }
 ?>
  <tr>
      <td colspan="3" align="right">Total Price:</td>
   <td><?php echo $total;?></td>
  </tr>
 <?php
 }else{
  echo "<b>Your Cart is Empty</b>";
 }
 ?>
 </table>

That's it Friends How to create PHP Shopping Cart..
Keep visiting ..Thank You..

No comments:

Post a Comment

Thank You for Your Comment

Note: Only a member of this blog may post a comment.