Pada tutorial yg lalu kita telah membuat database beserta table-table yang dibutuhkan untuk membangun toko online atau E-Commerce dengan php, membuat Persiapan Membuat Toko Online atau E-Commerce, Membuat CRUD untuk mengelola data user, Membuat CRUD table toko, Membuat halaman kategori produk, saatnya sekarang kita membuat form pembelian barang untuk melengkapi website e-commerce kita, form pembelian ini berhubungan dengan tabel tbl_pembelian, tbl_detail_pembelian dan table tbl_produk. Dari form pembelian ini kita akan melakukan update stok produk yang akan kita jual dan menentukan HPP(harga pokok penjualan) nantinya, tapi pada tutorial ini kita tidak akan membahas Hpp dahulu untuk memudahkan bagi pemula yang baru belajar membuat website e-commerce.
1.Membuat form add pembelian produk e-commerce
berikut code untuk menampilkan form add pembelian
<?php
include 'config.php';
error_reporting(0);
session_start();
if (empty($_SESSION['adminname'])) {
header("Location:login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin 2 - Charts</title>
<!-- Custom fonts for this template-->
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href="css/sb-admin-2.min.css" rel="stylesheet">
<!-- Custom styles for this page -->
<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
<script type="text/javascript" src="cart.js"></script>
<script>
function showEditBox(editobj,id) {
$('#frmAdd').hide();
$(editobj).prop('disabled','true');
var currentMessage = $("#message_" + id + " .message-content").html();
var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_'+id+'">'+currentMessage+'</textarea><button name="ok" onClick="callCrudAction(\'edit\','+id+')">Save</button><button name="cancel" onClick="cancelEdit(\''+currentMessage+'\','+id+')">Cancel</button>';
$("#message_" + id + " .message-content").html(editMarkUp);
}
function cancelEdit(message,id) {
$("#message_" + id + " .message-content").html(message);
$('#frmAdd').show();
}
function cartAction(action,product_code) {
var queryString = "";
if(action != "") {
switch(action) {
case "add":
queryString = 'action='+action+'&code='+ product_code+'&quantity='+$("#addqty").val()+'&harga='+$("#harga").val();
break;
case "remove":
queryString = 'action='+action+'&code='+ product_code;
break;
case "empty":
queryString = 'action='+action;
break;
}
}
jQuery.ajax({
url: "ajax_action.php",
data:queryString,
type: "POST",
success:function(data){
$("#cart-item").html(data);
if(action != "") {
switch(action) {
case "add":
//$("#add_"+product_code).hide();
//$("#added_"+product_code).show();
break;
case "remove":
$("#add_"+product_code).show();
$("#added_"+product_code).hide();
break;
case "empty":
$(".btnAddAction").show();
$(".btnAdded").hide();
break;
}
}
},
error:function (){}
});
}
</script>
<style>
.btnclass{color:#fff;background-color:#4e73df;border-color:#4e73df}
.btnclass:hover{color:#fff;background-color:#2e59d9;border-color:#2653d4}
.btnclass.focus,.btnclass:focus{color:#fff;background-color:#2e59d9;border-color:#2653d4;box-shadow:0 0 0 .2rem rgba(105,136,228,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#4e73df;border-color:#4e73df}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#2653d4;border-color:#244ec9}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>
.btnclass.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(105,136,228,.5)}
</style>
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<?php include('right_sidebar.php'); ?>
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<?php include('top_navbar.php'); ?>
<!-- Begin Page Content -->
<div class="container-fluid">
<form action="save_pembelian.php" method="POST" name="savebeli">
<div class="form-row">
<div class="form-group col-md-3">
<label for="inputEmail4">No Nota</label>
<input type="text" class="form-control" placeholder="input no nota" name="nota">
</div>
<div class="form-group col-md-3">
<label for="inputPassword4">Tanggal Pembelian</label>
<input class="form-control" id="date" name="date" placeholder="mm/dd/yyyy" type="text"/>
</div>
<div class="form-group col-md-3">
<label for="inputAddress">Toko</label>
<input class="form-control" type="text" id="nama_toko" name="nama_toko" placeholder="Nama Toko">
<input type="hidden" id="id_toko" name="idtoko">
</div>
</div>
<div class="form-group">
<label for="inputAddress2">Keterangan</label>
<textarea class="form-control" name="keterangan"></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
<form id="frmCart">
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputbarang">Nama Barang</label>
<input type="text" class="form-control" id="nama_barang" name="nama_barang" placeholder="input nama barang" required>
<input type="hidden" id="id_barang" name="idbarang">
</div>
<div class="form-group col-md-3">
<label for="inputbarang">Harga</label>
<input type="text" class="form-control" id="harga" name="harga" required>
</div>
<div class="form-group col-md-1">
<label for="inputbarang">Qty</label>
<input type="text" class="form-control" id="addqty" name="quantity" required >
</div>
<div class="form-group col-md-2">
<label for="inputbarang">Sub total</label>
<input type="text" class="form-control" id="subtotal" name="subtotal" readonly>
</div>
<div class="form-group col-md-2">
<button type="button" class="btnclass" style="margin-top:35px">Tambah Barang</button>
</div>
</div>
</form>
<div class="clear-float"></div>
<div id="shopping-cart">
<center><div class="txt-heading" style="margin-top:20px;">Item Pembelian Barang<a id="btnEmpty" class="cart-action" onClick="cartAction('empty','');"> - Kosongkan item</a></div></center>
<div id="cart-item"></div>
</div>
<hr>
<div style="margin-top:20px;">
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © Your Website 2020</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true" data-backdrop="static">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="login.html">Logout</a>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin-2.min.js"></script>
<!-- Page level plugins -->
<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<!-- Page level custom scripts -->
<script src="js/demo/datatables-demo.js"></script>
<!-- Extra JavaScript/CSS added manually in "Settings" tab -->
<!-- Include jQuery -->
<script type="text/javascript" src="https://localhost/fashion/admin/tuhu/jquery-1.11.3.min.js"></script>
<!-- Include Date Range Picker -->
<script type="text/javascript" src="https://localhost/fashion/admin/tuhu/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="http://localhost/fashion/admin/tuhu/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="http://localhost/fashion/admin/tuhu/jquery-ui.css">
<script src="https://localhost/fashion/admin/tuhu/jquery-1.12.4.js"></script>
<script src="https://localhost/fashion/admin/tuhu/jquery-ui.js"></script>
<script>
$(document).ready(function(){
cartAction('','');
//menampilkan datepicker
var date_input=$('input[name="date"]'); //our date input has the name "date"
var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'mm/dd/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
})
//Autocomplete untuk table toko / suplier
$( function() {
$("#nama_toko").autocomplete({
minLength: 0,
source: "fetchData.php",
select: function(event, ui) {
$("#id_toko").val(ui.item.id);
}
})
}),
//Autocomplete untuk table barang dan langsung mengisi data barangnya
$( function() {
$("#nama_barang").autocomplete({
minLength: 0,
source: "fetchDataBarang.php",
select: function(event, ui) {
var idvalue = document.getElementById("id_barang");
$("#id_barang").val(ui.item.id);
//$("#harga").val(ui.item.hrg);
//menambah atribut id di button class btnclass
$('.btnclass').attr('id', "add_"+ui.item.id);
// $('.quantity2').prop('id', "add_"+ui.item.id);
// $('.quantity2').prop('type', "text");
$('.btnclass').attr('onClick', "cartAction("+("'add','"+ui.item.id)+"')");
}
})
}),
$('#addqty').keyup(function()
{
var qty = document.getElementById('addqty').value;
var hrg = document.getElementById('harga').value;
var total = Number(qty) * Number(hrg);
document.getElementById('subtotal').value = total ;
}
)
/*
$('#harga').keyup(function()
{
document.getElementById('harga').value = <?php echo 1; ?> ;
}
)
*/
});
</script>
</body>
</html>
2.Membuat file fetchData.php
File fetchData.php berguna untuk Autocomplete dalam input data toko atau suplier pada form add pembelian seperti gambar dibawah ini
<?php
include 'config.php';
$searchTerm = $_GET['term'];
$sql = "SELECT * FROM tbl_toko WHERE nama LIKE '%".$searchTerm."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$tutorialData = array();
while($row = $result->fetch_assoc()) {
$data['id'] = $row['id'];
$data['value'] = $row['nama'];
array_push($tutorialData, $data);
}
}
echo json_encode($tutorialData);
?>
3.Membuat file fetchDataBarang.php
File yang akan kita buat ini berguna untuk autocomplete input untuk data barang sehingga memudahkan user untuk memilih data barang yang akan di beli, berikut codenya dan simpan dengan nama fetchDataBarang.php
<?php
include 'config.php';
$searchTerm2 = $_GET['term'];
$sql2 = "SELECT * FROM tbl_produk WHERE nama_produk LIKE '%".$searchTerm2."%'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
$tutorialData2 = array();
while($row2 = $result2->fetch_assoc()) {
$data2['id'] = $row2['id_produk'];
$data2['value'] = $row2['nama_produk'];
$data2['hrg'] = $row2['harga'];
array_push($tutorialData2, $data2);
}
}
echo json_encode($tutorialData2);
?>
4.Membuat file ajax_action.php
Kita akan menggunakan ajax dalam proses pembuatan form add pembelian produk ini, misalnya dalam menghandel item produk yang di beli, sehingga setiap save item produk tidak perlu lagi reload browsernya sehingga proses input produk menjadi lebih cepat dan efisien. berikut codenya dan simpan dengan nama ajax_action.php
<?php
session_start();
require_once("config.php");
global $item_total;
function runQuery($query,$conn) {
$result = mysqli_query($query, $conn);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query,$conn) {
$result = mysqli_query($conn, $query);
$rowcount = mysql_num_rows($result);
return $rowcount;
}
if(!empty($_POST["action"])) {
switch($_POST["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
//echo '<script>alert("'.$_POST["quantity"].'")</script>';
$productByCode = mysqli_query($conn,"SELECT * FROM tbl_produk WHERE id_produk='" . $_POST["code"] . "'");
$productByCode = mysqli_fetch_array($productByCode);
$itemArray = array($productByCode["id_produk"]=>array('name'=>$productByCode["nama_produk"], 'code'=>$productByCode["id_produk"], 'quantity'=>$_POST["quantity"], 'price'=>$_POST["harga"]));
//cek apakah session cart_item sdh ada atau blm
if(!empty($_SESSION["cart_item"])) {
$id = array();
foreach ($_SESSION['cart_item'] as $item) {
$id[] = $item['code'];
}
//mencari apakah barang sudah ada di cart atau belum
if(in_array($_POST['code'], $id))
{
//jika barang sdh ada di dalam cart, update qty
foreach($_SESSION["cart_item"] as $k => $v) {
if($_POST["code"] === $v["code"])
{
//$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
echo "<script>alert('Barang sudah ada dalam item pembelian, untuk melakukan perubahan, silahkan hapus item barang lalu input dengan data yang baru')</script>";
}
}
} else {
//jika barang blm ada di dalam cart, tambah data baru di cart
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
//jika cart masih kosong/blm ada data, tambah data baru di cart
$_SESSION["cart_item"] = $itemArray;
}
?>
<script>
document.getElementById('addqty').value=0;
document.getElementById('id_barang').value='';
document.getElementById('harga').value=0;
document.getElementById('subtotal').value=0;
document.getElementById('nama_barang').value='';
</script>
<?php
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
//echo '<script>alert("'.$_POST["code"].'")</script>';
if($_POST["code"] == $v["code"])
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th><strong>Sub Total</strong></th>
<th><strong>Action</strong></th>
</tr>
</thead>
<tbody>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["code"]; ?></td>
<td><?php echo $item["quantity"]; ?></td>
<td align=right><?php echo $item["price"]; ?></td>
<td><?php echo $item["price"]*$item["quantity"]; ?></td>
<td><a onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction cart-action">Remove Item</a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total Pembelian:</strong> <?php echo "RP".$item_total; ?></td>
</tr>
<tbody>
</table>
</div>
<?php
}
?>
5.Membuat file save_pembelian.php
Langkah terakhir adalah membuat file save_pembelian.php yang berguna untuk menyimpan data yang telah diinput oleh user, kita menggunakan metode transaction dalam menyimpan datanya karena kita akan menyimpan datanya di ke 3 table yaitu, tbl_pembelian, tbl_detail_pembelian dan tbl_produk(update stok produk dengan quantity pembelian), jika menggunakan metode transaction, jika terjadi error dengan salah satu proses penyimpanannya maka akan di rollback secara otomatis sehingga data tidak akan tersimpan ke dalam 3 table kerana terjadi error pada salah satu prosesnya.berikut codenya save dengan nama save_pembelian.php
<?php
session_start();
require 'config.php';
//Simpan pesanan baru
global $item_total2;
$nota=$_POST['nota'];
//$tgl=$_POST['date'];
$tgl = date('Y-m-d', strtotime($_POST['date']));
$toko=$_POST['idtoko'];
$item_total2=0;
$keterangan=$_POST['keterangan'];
//$sql1 = 'INSERT INTO tbl_pembelian(no_nota, tgl_beli, id_toko, total, keterangan) VALUES ('.$nota.', '.$tgl.', '.$toko.', '.$total.', '.$keterangan.')';
//mysqli_query($conn, $sql1);
foreach ($_SESSION["cart_item"] as $item2) {
$item_total2 += ($item2["price"] * $item2["quantity"]);
}
$grandtotal=floatval($item_total2);
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
/* Start transaction */
mysqli_begin_transaction($conn);
try {
mysqli_query($conn, "INSERT INTO tbl_pembelian(no_nota, tgl_beli, id_toko, total, keterangan) VALUES ('$nota', '$tgl', '$toko', $grandtotal, '$keterangan')");
$ordersid = mysqli_insert_id($conn);
//$cart = unserialize(serialize($_SESSION['cart_item'])); //Set $cart sebagai array, serialize () mengubah string menjadi array
foreach ($_SESSION["cart_item"] as $item) {
//$sql2 = 'INSERT INTO tbl_detail_pembelian(id_pembelian, id_produk, qty, harga, total) VALUES ('.$ordersid.', '.$cart[$i]->code.', '.$cart[$i]->quantity.', '.$cart[$i]->price.', '.($cart[$i]->price * $cart[$i]->quantity).')';
//mysqli_query($conn, $sql2);
mysqli_query($conn, 'INSERT INTO tbl_detail_pembelian(id_pembelian, id_produk, qty, harga, total) VALUES ('.$ordersid.', '.$item["code"].', '.$item["quantity"].', '.$item["price"].', '.($item["price"] * $item["quantity"]).')');
mysqli_query($conn, 'update tbl_produk set stok=stok+'.$item["quantity"].' where id_produk='.$item["code"].'');
}
if(mysqli_commit($conn))
{
echo "<script>alert('Data Sudah Disimpan')</script>";
unset($_SESSION["cart_item"]);
echo "<script>window.location.href ='add_pembelian.php' </script>";
}
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($conn);
echo "<script>alert('Data gagal Disimpan')</script>";
echo "<script>window.location.href ='add_pembelian.php' </script>";
//show the error
//throw $exception;
}
?>
Demikian tutorial pembuatan form pembelian barang untuk website e-commerce, happy coding