Create a product purchase form for e-commerce

In the last tutorial we have created a database along with the tables needed to build an online store or E-Commerce with php, made Preparations for Creating an Online Store or E-Commerce, Created a CRUD to manage user data, Created a store table CRUD, Created a category page product, it’s time now for us to make a purchase form to complete our e-commerce website, this purchase form is related to the tbl_pembelian table, tbl_detail_pembelian and the tbl_product table. From this purchase form we will update the product stock that we will sell and determine the cost of goods sold later, but in this tutorial we will not discuss the the cost of goods sold to make it easier for new beginners.

1.Create an add purchase form for e-commerce products

The code of add purchase form

<?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 &copy; 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.Create fetchData.php

The fetchData.php is useful for Autocomplete in entering shop or supplier data on the input in add purchase form as shown below

autocomplete toko
autocomplete shop or supplier – photo by webbaliseo.com
<?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);
?>

4. Create a fetchData Barang.php

fetchDataBarang.php is useful for autocomplete input for item data of products that is making it easier for the user to select the item data of product to be purchased

autocomplete produk
autocomplete of product – photo by webbaliseo.com
<?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);
?>

5.Create an ajax_action.php

We will use ajax to processing of making the add purchase form for this product, for example in handling purchased product items, so that every save product item no longer needs to reload the browser so that the product input process becomes faster and more efficient. here is the code and save it with the name 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
}
?>

6. Create save_pembelian.php

The last step is create a save_pembelian.php file, which is useful for storing data that has been inputted by the user, we use the transaction method to save the data because we will store the data in 3 tables( tbl_purchase, tbl_detail_purchase and tbl_product) update product stock with purchase quantity, if using the transaction method, if there is an error with one of the storage processes it will be rolled back automatically so that the data will not be saved in 3 tables because an error occurred in one of the processes. The following code is saved with the name 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;

}
 ?>

Thus the tutorial for making a product purchase form for an e-commerce website, happy coding

Leave a Reply

Your email address will not be published. Required fields are marked *