Membuat Shopping Cart Simple Menggunakan PHP

//lh4.googleusercontent.com/-eAXyxy2JJKA/AAAAAAAAAAI/AAAAAAAAGS4/OHgzqHzCvtQ/s512-c/photo.jpg
October 09, 2018

Selamat pagi sobat blogger kali ini kami akan share bagaimana membuat shopping cart simple menggunakan PHP, disamping itu kami menggunakan bootsrap sebagai kerangka tampilan pada app shopping cart.



Langsung saa yang pertama kita diharuskan membuat database, buat database dengan nama shopping kemudian masukkan struktur database dibawah ini.

 
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `price` double NOT NULL,
  `photo` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `products` (`id`, `name`, `price`, `photo`) VALUES
(1, 'DELL Inspiron 15 7000 15.6', 899, 'images/1.jpg'),
(2, 'MICROSOFT Surface Pro 4 & Typecover - 128 GB', 799, 'images/2.jpg'),
(3, 'DELL Inspiron 15 5000 15.6', 599, 'images/3.jpg'),
(4, 'LENOVO Ideapad 320s-14IKB 14\" Laptop - Grey', 399, 'images/4.jpg');


ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);


ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
COMMIT;
 

Buat file dengan nama index.php, file ini akan berfungsi untuk menampilkan produk dan pada file ini terdapat form_modal untuk menambahkan produk.


 <?php
session_start();
 //initialize cart if not set or is unset
if(!isset($_SESSION['cart'])){
 $_SESSION['cart'] = array();
}

 //unset qunatity
unset($_SESSION['qty_array']);
?>
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>Hopping Cart</title>
 <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
 <style>
 .product_image{
  height:200px;
 }
 .product_name{
  height:80px; 
  padding-left:20px; 
  padding-right:20px;
 }
 .product_footer{
  padding-left:20px; 
  padding-right:20px;
 }
</style>
</head>
<body>
 <br/>
 <div class="container">
  <nav class="navbar navbar-default">
   <div class="container-fluid">
    <div class="navbar-header">
     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
     </button>
     <a class="navbar-brand" href="#">Shopping Cart</a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
     <ul class="nav navbar-nav">
      <!-- left nav here -->
     </ul>
     <ul class="nav navbar-nav navbar-right">
      <li><a href="view_cart.php"><span class="badge"><?php echo count($_SESSION['cart']); ?></span> Cart <span class="glyphicon glyphicon-shopping-cart"></span></a></li>
     </ul>
    </div>
   </div>
  </nav>
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#form_modal"><span class="glyphicon glyphicon-plus"></span> Add Product</button>
  <p/>
  <?php
  //info message
  if(isset($_SESSION['message'])){
   ?>
   <div class="row">
    <div class="col-sm-6 col-sm-offset-6">
     <div class="alert alert-info text-center">
      <?php echo $_SESSION['message']; ?>
     </div>
    </div>
   </div>
   <?php
   unset($_SESSION['message']);
  }


  //connection
  $conn = new mysqli('localhost', 'root', '', 'shopping');

  $sql = "SELECT * FROM products";
  $query = $conn->query($sql);
  $inc = 4;
  while($row = $query->fetch_assoc()){
   $inc = ($inc == 4) ? 1 : $inc + 1; 
   if($inc == 1) echo "<div class='row text-center'>";  
   ?>
   <div class="col-sm-3">
    <div class="panel panel-default">
     <div class="panel-body">
      <div class="row product_image">
       <img src="<?php echo $row['photo'] ?>" width="80%" height="auto">
      </div>
      <div class="row product_name">
       <h4><?php echo $row['name']; ?></h4>
      </div>
      <div class="row product_footer">
       <p class="pull-left"><b><?php echo $row['price']; ?></b></p>
       <span class="pull-right"><a href="add_cart.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm"><span class="glyphicon glyphicon-plus"></span> Cart</a></span>
      </div>
     </div>
    </div>
   </div>
   <?php
  }
  if($inc == 1) echo "<div></div><div></div><div></div></div>"; 
  if($inc == 2) echo "<div></div><div></div></div>"; 
  if($inc == 3) echo "<div></div></div>";
  
  //end product row 
  ?>

 </div>

   <div class="modal fade" id="form_modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
   <form action="save_query.php" method="POST" enctype="multipart/form-data">
    <div class="modal-content">
     <div class="modal-body">
      <div class="col-md-2"></div>
      <div class="col-md-8">
       <div class="form-group">
        <label>Product Name</label>
        <input class="form-control" type="text" name="name">
       </div>
       <div class="form-group">
        <label>Product Price</label>
        <input class="form-control" type="number" name="price">
       </div>
       <div class="form-group">
        <label>Product Photo</label>
        <input class="form-control" type="file" name="photo">
       </div>
      </div>
     </div>
     <div style="clear:both;"></div>
     <div class="modal-footer">
      <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
      <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
     </div>
    </div>
   </form>
  </div>
 </div>
</body>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.js"></script>
</html> 

Berikutnya buat file dengan nama add_cart.php file ini berisi script berfungsi sebagai add to chart.

 <?php
 session_start();

 //periksa apakah produk sudah ada dalam keranjang
 if(!in_array($_GET['id'], $_SESSION['cart'])){
  array_push($_SESSION['cart'], $_GET['id']);
  $_SESSION['message'] = 'Product added to cart';
 }
 else{
  $_SESSION['message'] = 'Product already in cart';
 }

 header('location: index.php');
?> 



Gambat diatas merupakan tampilan view cart, Berikutnya buat file dengan nama view_cart.php file ini berfungsi ini berisi cript yang berfungsi untuk menampilkan produk yang ada pada keranjangnya.

 <?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>Shopping Cart</title>
 <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
</head>
<body>
 <br/>
 <div class="container">
  <nav class="navbar navbar-default">
   <div class="container-fluid">
    <div class="navbar-header">
     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
     </button>
     <a class="navbar-brand" href="#">Shopping Cart</a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
     <ul class="nav navbar-nav">
      <!-- left nav here -->
     </ul>
     <ul class="nav navbar-nav navbar-right">
      <li class="active"><a href="view_cart.php"><span class="badge"><?php echo count($_SESSION['cart']); ?></span> Cart <span class="glyphicon glyphicon-shopping-cart"></span></a></li>
     </ul>
    </div>
   </div>
  </nav>
  <div class="row">
   <div class="col-sm-8 col-sm-offset-2">
    <?php 
    if(isset($_SESSION['message'])){
     ?>
     <div class="alert alert-info text-center">
      <?php echo $_SESSION['message']; ?>
     </div>
     <?php
     unset($_SESSION['message']);
    }

    ?>
    <form method="POST" action="save_cart.php">
     <table class="table table-bordered table-striped">
      <thead>
       <th></th>
       <th>Name</th>
       <th>Price</th>
       <th>Quantity</th>
       <th>Subtotal</th>
      </thead>
      <tbody>
       <?php
      //initialize total
       $total = 0;
       if(!empty($_SESSION['cart'])){
      //connection
        $conn = new mysqli('localhost', 'root', '', 'shopping');
      //create array of initail qty which is 1
        $index = 0;
        if(!isset($_SESSION['qty_array'])){
         $_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1);
        }
        $sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
        $query = $conn->query($sql);
        while($row = $query->fetch_assoc()){
         ?>
         <tr>
          <td>
           <a href="delete_item.php?id=<?php echo $row['id']; ?>&index=<?php echo $index; ?>" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-trash"></span></a>
          </td>
          <td><?php echo $row['name']; ?></td>
          <td><?php echo number_format($row['price'], 2); ?></td>
          <input type="hidden" name="indexes[]" value="<?php echo $index; ?>">
          <td><input type="text" class="form-control" value="<?php echo $_SESSION['qty_array'][$index]; ?>" name="qty_<?php echo $index; ?>"></td>
          <td><?php echo number_format($_SESSION['qty_array'][$index]*$row['price'], 2); ?></td>
          <?php $total += $_SESSION['qty_array'][$index]*$row['price']; ?>
         </tr>
         <?php
         $index ++;
        }
       }
       else{
        ?>
        <tr>
         <td colspan="4" class="text-center">No Item in Cart</td>
        </tr>
        <?php
       }

       ?>
       <tr>
        <td colspan="4" align="right"><b>Total</b></td>
        <td><b><?php echo number_format($total, 2); ?></b></td>
       </tr>
      </tbody>
     </table>
     <a href="index.php" class="btn btn-primary"><span class="glyphicon glyphicon-arrow-left"></span> Back</a>
     <button type="submit" class="btn btn-success" name="save">Save Changes</button>
     <a href="clear_cart.php" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Clear Cart</a>
     <a href="checkout.php" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Checkout</a>
    </form>
   </div>
  </div>
 </div>
</body>
</html> 

Buat file dengan nama save_query.php, file ini berisi script untuk menambahkan produk kedalam database.

 <?php
 $conn = new mysqli('localhost', 'root', '', 'shopping');
 
 if(ISSET($_POST['save'])){
  if(!empty($_POST['name']) && !empty($_POST['price'])){
   $name = addslashes($_POST['name']);
   $price = $_POST['price'];
 
   $file = explode(".", $_FILES['photo']['name']);
   $ext = array("png", "gif", "jpg", "jpeg");
 
   if(in_array($file[1], $ext)){
    $file_name = $file[0].'.'.$file[1];
    $tmp_file = $_FILES['photo']['tmp_name'];
    $location = "images/".$file_name;
    $new_location = addslashes($location);
 
    if(move_uploaded_file($tmp_file, $location)){
     $conn->query("INSERT INTO `products` VALUES('', '$name', '$price', '$new_location')");
     echo "<script>alert('Data Insert')</script>";
     echo "<script>window.location = 'index.php'</script>";
    }
 
   }else{
    echo "<script>alert('File not available')</script>";
    echo "<script>window.location = 'index.php'</script>";
   }
 
  }else{
   echo "<script>alert('Please complete the required field!')</script>";
  }
 
 
 }
?> 

Berikutnya buat file dengan nama delete_item.php file ini berfungsi untuk menghapus item dari keranjang yang sudah ditambahkan.

 <?php
 session_start();

 //hapus id dari larik keranjang kami
 $key = array_search($_GET['id'], $_SESSION['cart']); 
 unset($_SESSION['cart'][$key]);

 unset($_SESSION['qty_array'][$_GET['index']]);
 //mengatur ulang array setelah tidak disetel
 $_SESSION['qty_array'] = array_values($_SESSION['qty_array']);

 $_SESSION['message'] = "Product deleted from cart";
 header('location: view_cart.php');
?> 

Berikutnya buat file dengan nama save_cart.php file ini berisi script yang berfungsi untuk menyimpan produk yang ditambahkan atau produk yang telah di edit pada produk keranjang.

 <?php
 session_start();
 if(isset($_POST['save'])){
  foreach($_POST['indexes'] as $key){
   $_SESSION['qty_array'][$key] = $_POST['qty_'.$key];
  }

  $_SESSION['message'] = 'Cart updated successfully';
  header('location: view_cart.php');
 }
?>
 

Berikutnya buat file dengan nama clear_cart.php file ini berisi script yang berfungsi untuk membersihkan semua isi keranjang.

 <?php
 session_start();
 unset($_SESSION['cart']);
 $_SESSION['message'] = 'Cart cleared successfully';
 header('location: index.php');
?> 

Berikutnya buat file dengan nama checkout.php. Dalam fungsi umum checkout ini akan mengarahkan user atau pelanggan ke halaman login untuk mengisi identitas secara details. Tetapi dalam fungsi ini checkout ini akan menampilkan pesan bahwa belanjaan yang ada di keranjangnya.

 <?php
 session_start();
 //pengguna perlu login untuk checkout
 $_SESSION['message'] = 'You need to login to checkout';
 header('location: view_cart.php');
?> 

Kalian bisa langsung melihat demo dan bisa langsung dan mendownload filenya untuk bisa langsung mencoba dan mempelajarinya langsung.

DEMO       DOWNLOAD

Sekian share kali ini semoga apa yang kami share bermanfaat bagi anda, Jika kalian belum paham bisa meningggalkan komentar dibawah dan mulai berdiskusi dengan kami.


Artikel Menarik Lainnya

SUBSCRIBE TO OUR NEWSLETTER