Pada kesempatan ini dalam Cara Membuat Shopping Cart Menggunakan PHP, dimana sebelumnya kita sudah membuat database serta tabel-tabel uang dibutuhkan. Lalu kita sudah membuat sebuah file index.php, config.php, dan cart.php. Pada file cart.php adalah sebuah class libary Cart yang terdiri beberapa function. Function yang dibuat seperti insert,update,delete. Serta ada proses perhitungan untuk item atau barang yang dimasukan kedalam keranjang dan ada function remove atau reset isi keranjang.
JIka pada langkah sebelunya sudah membuat sebuah class cart maka selanjutnya kita membuat sebuah file action dan berikan nama file Action_cart.php :
<?php
require_once 'Cart.php';
$cart = new Cart;
require_once 'Config.php';
$redirectLoc = 'index.php';
if(isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
if($_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
$productID = $_REQUEST['id'];
$query = $db->query("SELECT * FROM art_products WHERE id = ".$productID);
$row = $query->fetch_assoc();
$itemData = array(
'id' => $row['id'],
'name' => $row['name'],
'price' => $row['price'],
'qty' => 1
);
$insertItem = $cart->insert($itemData);
$redirectLoc = $insertItem?'View_cart.php':'index.php';
}elseif($_REQUEST['action'] == 'updateCartItem' && !empty($_REQUEST['id'])){
$itemData = array(
'rowid' => $_REQUEST['id'],
'qty' => $_REQUEST['qty']
);
$updateItem = $cart->update($itemData);
echo $updateItem?'ok':'err';die;
}elseif($_REQUEST['action'] == 'removeCartItem' && !empty($_REQUEST['id'])){
$deleteItem = $cart->remove($_REQUEST['id']);
$redirectLoc = 'View_cart.php';
}elseif($_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0){
$redirectLoc = 'Checkout.php';
$_SESSION['postData'] = $_POST;
$first_name = strip_tags($_POST['first_name']);
$last_name = strip_tags($_POST['last_name']);
$email = strip_tags($_POST['email']);
$phone = strip_tags($_POST['phone']);
$address = strip_tags($_POST['address']);
$errorMsg = '';
if(empty($first_name)){
$errorMsg .= 'Please enter your first name.<br/>';
}
if(empty($last_name)){
$errorMsg .= 'Please enter your last name.<br/>';
}
if(empty($email)){
$errorMsg .= 'Please enter your email address.<br/>';
}
if(empty($phone)){
$errorMsg .= 'Please enter your phone number.<br/>';
}
if(empty($address)){
$errorMsg .= 'Please enter your address.<br/>';
}
if(empty($errorMsg)){
$insertCust = $db->query("INSERT INTO art_customers (first_name, last_name, email, phone, address) VALUES ('".$first_name."', '".$last_name."', '".$email."', '".$phone."', '".$address."')");
if($insertCust){
$custID = $db->insert_id;
$insertOrder = $db->query("INSERT INTO art_orders (customer_id, grand_total, created, status) VALUES ($custID, '".$cart->total()."', NOW(), 'Pending')");
if($insertOrder){
$orderID = $db->insert_id;
$cartItems = $cart->contents();
$sql = '';
foreach($cartItems as $item){
$sql .= "INSERT INTO art_order_items (order_id, product_id, quantity) VALUES ('".$orderID."', '".$item['id']."', '".$item['qty']."');";
}
$insertOrderItems = $db->multi_query($sql);
if($insertOrderItems){
$cart->destroy();
$redirectLoc = 'Order_success.php?id='.$orderID;
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
}
}else{
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Please fill all the mandatory fields.<br>'.$errorMsg;
}
$_SESSION['sessData'] = $sessData;
}
}
header("Location: $redirectLoc");
exit();
Pada code diatas berisi perintah SQL untuk proses CRUD kedalam tabel art_order, art_order_item serta art_customer. Jadi saat item yang sudah dipilih akan langsung masuk kedalam keranjang belanja.
Langkah selanjutnya adalah membuat sebuah view product yang ada dalam keranjang belanja berikut codenya:
<?php
include_once 'Cart.php';
$cart = new Cart;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Membuat Shopping Cart Menggunakan PHP</title>
<meta charset="utf-8">
<!-- Bootstrap core CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom style -->
<link href="style.css" rel="stylesheet">
<!-- Fontawesome Icon -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function updateCartItem(obj,id){
$.get("Action_cart.php", {action:"updateCartItem", id:id, qty:obj.value}, function(data){
if(data == 'ok'){
location.reload();
}else{
alert('Cart update failed, please try again.');
}
});
}
</script>
</head>
<body>
<div class="container">
<h1>SHOPPING CART</h1>
<div class="row">
<div class="cart">
<div class="col-12">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th width="45%">Product</th>
<th width="10%">Price</th>
<th width="15%">Quantity</th>
<th class="text-right" width="20%">Total</th>
<th width="10%"> </th>
</tr>
</thead>
<tbody>
<?php
if($cart->total_items() > 0){
$cartItems = $cart->contents();
foreach($cartItems as $item){
?>
<tr>
<td><?php echo $item["name"]; ?></td>
<td><?php echo 'Rp. '.number_format($item["price"],0, '.','.'); ?></td>
<td><input class="form-control" type="number" value="<?php echo $item["qty"]; ?>" onchange="updateCartItem(this, '<?php echo $item["rowid"]; ?>')"/></td>
<td class="text-right">
<?php echo 'Rp. '.number_format($item["subtotal"],0, '.','.'); ?>
</td>
<td class="text-right"><button class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')?window.location.href='Action_cart.php?action=removeCartItem&id=<?php echo $item["rowid"]; ?>':false;"><i class="fas fa-trash-alt"></i> </button> </td>
</tr>
<td></td>
<td></td>
<td><strong>Cart Total</strong></td>
<td class="text-right"><strong>
<?php echo 'Rp. '.number_format($cart->total(),0, '.','.'); ?>
</strong>
</td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div class="col mb-2">
<div class="row">
<div class="col-sm-12 col-md-6">
<a href="index.php" class="btn btn-block btn-light">Continue Shopping</a>
</div>
<div class="col-sm-12 col-md-6 text-right">
<?php if($cart->total_items() > 0){ ?>
<a href="Checkout.php" class="btn btn-lg btn-block btn-primary">Checkout</a>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Baiklah jika sudah coba sahabat jalankan pada browser pilih item product kemudian coba tambahkan atau kurangi jumlah quatitynya, jika benar maka sudah berhasil atau fungsi yang sudah berjalan.
Baiklah saya akan lanjutkan lagi pada pembahasan artikel selanjutnya untuk proses checkout dan status pembeliannya.
terima kasih