Cara membuat shopping cart dengan php

Di era digital seperti sekarang ini sebuah website ecommerce atau toko online harus memiliki fitur shopping cart dapat dikatakan shopping cart wajib hukumnya, karena fitur shopping cart ini akan memudahkan pengunjung untuk melakukan transaksi online di sebuah website ecommerce atau toko online.

DAFTAR ISI :
1. Pengenalan
2. Pembuatan Database and Table in MySQL
3. Struktur file
4. Membuat style.css 
5. Membuat file functions.php
6. Membuat file index.php 
7. Membuat file home.php 
8. Membuat file products.php
9. Membuat file product.php
10.Membuat shopping cart page / cart.php
11.Membuat halaman place order /placeorder.php
12.Penutup

1. PENGENALAN

Dalam tutorial kali ini kita akan membuat sistem shopping cart dengan PHP dan MySQL. Sistem shopping cart akan memungkinkan pengunjung situs web kita untuk menelusuri produk, menambahkan produk ke keranjang, dan memesan secara online tentunya.

kita akan menggunakan antarmuka PDO untuk mengakses database MySQL kita dengan PHP karena akan memudahkan kita untuk berinteraksi dengan database kita dan memanipulasi tabel kita.

Sistem shopping cart yang akan kita buat akan berisi 4 produk dulu untuk memudahkan kita berlatih, nanti klu sudah mahir bisa ditambah lagi produknya. Produk-produk ini pada dasarnya hanyalah digunakan sebagai contoh untuk tutorial ini. Anda dapat menambahkan produk Anda sendiri nanti.

 

2. PEMBUATAN DATABASE DAN TABLE DI MySQL

2.1 Pembuatan Database ‘shoppingcart’

kita akan membuat 1 database dengan nama ‘shoppingcart’, masuk ke halaman http://localhost/phpmyadmin/ untuk membuat databasenya, untuk membuat databasenya jalankan perintah SQL berikut ‘CREATE DATABASE shoppingcart;’ di SQL querynya. seperti gambar dibawah ini.

Cara membuat shopping cart dengan php

2.2. Pembuatan Table `products`

Setelah berhasil membuat databasenya kita lanjut membuat tablenya. ikuti langkah-langkah dibawah ini :

CREATE TABLE IF NOT EXISTS `products` (
	`id` int(11) NOT NULL AUTO_INCREMENT,
	`name` varchar(200) NOT NULL,
	`desc` text NOT NULL,
	`price` decimal(7,2) NOT NULL,
	`rrp` decimal(7,2) NOT NULL DEFAULT '0.00',
	`quantity` int(11) NOT NULL,
	`img` text NOT NULL,
	`date_added` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
	PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `products` (`id`, `name`, `desc`, `price`, `rrp`, `quantity`, `img`, `date_added`) VALUES
(1, 'Smart Watch', '

Unique watch made with stainless steel, ideal for those that prefer interative watches.

\r\n

Features

\r\n
    \r\n
  • Powered by Android with built-in apps.
  • \r\n
  • Adjustable to fit most.
  • \r\n
  • Long battery life, continuous wear for up to 2 days.
  • \r\n
  • Lightweight design, comfort on your wrist.
  • \r\n
', '29.99', '0.00', 10, 'watch.jpg', '2019-03-13 17:55:22'), (2, 'Wallet', '', '14.99', '19.99', 34, 'wallet.jpg', '2019-03-13 18:52:49'), (3, 'Headphones', '', '19.99', '0.00', 23, 'headphones.jpg', '2019-03-13 18:47:56'), (4, 'Digital Camera', '', '69.99', '0.00', 7, 'camera.jpg', '2019-03-13 17:42:04');
Cara membuat shopping cart dengan php
Di phpmyadmin akan kelihatan seperti ini

Kode pernyataan SQL di atas akan membuat tabel produk dengan kolom berikut :

id — Unique ID untuk product, ini kita setting auto incremented.
name — Nama dari product.
desc — Penjelasan dari product.
price — harga dari product.
rrp —Harga eceran, jika Anda ingin produk dijual, Anda menempatkan nilai lebih tinggi dari harga.
date_added — Tanggal produk ditambahkan, kami akan menggunakan ini untuk menyortir produk.

Pernyataan SQL diatas juga akan memasukkan 4 contoh produk yang dapat kita gunakan untuk tujuan pengujian. Anda dapat mengubah/menghapusnya nanti di tutorial saat kita telah mengimplementasikan kodenya.

3. STRUKTUR FILE DAN FOLDER

Untuk struktur file dan folder pada project yang akan kita buat seperti gambar dibawah ini :

Cara membuat shopping cart dengan php
 

4. MEMBUAT FILE STYLE.CSS

File ini berguna untuk berfungsi untuk mengatur tampilan setiap elemen yang tertulis dalam bahasa markup / HTML. Fungsi lain dari CSS yakni untuk memisahkan konten dari tampilan visual dalam sebuah website.

tuliskan kode berikut dan simpan dengan nama style.css

* {
	box-sizing: border-box;
	font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell, "fira sans", "droid sans", "helvetica neue", Arial, sans-serif;
	font-size: 16px;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}
html {
	height: 100%;
}
body {
	position: relative;
	min-height: 100%;
	color: #555555;
	background-color: #FFFFFF;
	margin: 0;
	padding-bottom: 100px; /* Same height as footer */
}
h1, h2, h3, h4, h5 {
	color: #394352;
}
.content-wrapper {
	width: 1050px;
	margin: 0 auto;
}
header {
	border-bottom: 1px solid #EEEEEE;
}
header .content-wrapper {
	display: flex;
}
header h1 {
	display: flex;
	flex-grow: 1;
	flex-basis: 0;
	font-size: 20px;
	margin: 0;
	padding: 24px 0;
}
header nav {
	display: flex;
	flex-grow: 1;
	flex-basis: 0;
	justify-content: center;
	align-items: center;
}
header nav a {
	text-decoration: none;
	color: #555555;
	padding: 10px 10px;
	margin: 0 10px;
}
header nav a:hover {
	border-bottom: 1px solid #aaa;
}
header .link-icons {
	display: flex;
	flex-grow: 1;
	flex-basis: 0;
	justify-content: flex-end;
	align-items: center;
	position: relative;
}
header .link-icons a {
	text-decoration: none;
	color: #394352;
	padding: 0 10px;
}
header .link-icons a:hover {
	color: #4e5c70;
}
header .link-icons a i {
	font-size: 18px;
}
header .link-icons a span {
	display: inline-block;
	text-align: center;
	background-color: #63748e;
	border-radius: 50%;
	color: #FFFFFF;
	font-size: 12px;
	line-height: 16px;
	width: 16px;
	height: 16px;
	font-weight: bold;
	position: absolute;
	top: 22px;
	right: 0;
}
main .featured {
	display: flex;
	flex-direction: column;
	background-image: url(imgs/featured-image.jpg);
	background-repeat: no-repeat;
	background-size: cover;
	height: 500px;
	align-items: center;
	justify-content: center;
	text-align: center;
}
main .featured h2 {
	display: inline-block;
	margin: 0;
	width: 1050px;
	font-family: Rockwell, Courier Bold, Courier, Georgia, Times, Times New Roman, serif;
	font-size: 68px;
	color: #FFFFFF;
	padding-bottom: 10px;
}
main .featured p {
	display: inline-block;
	margin: 0;
	width: 1050px;
	font-size: 24px;
	color: #FFFFFF;
}
main .recentlyadded h2 {
	display: block;
	font-weight: normal;
	margin: 0;
	padding: 40px 0;
	font-size: 24px;
	text-align: center;
	width: 100%;
	border-bottom: 1px solid #EEEEEE;
}
main .recentlyadded .products, main .products .products-wrapper {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	justify-content: space-between;
	padding: 40px 0 0 0;
}
main .recentlyadded .products .product, main .products .products-wrapper .product {
	display: block;
	overflow: hidden;
	text-decoration: none;
	width: 25%;
	padding-bottom: 60px;
}
main .recentlyadded .products .product img, main .products .products-wrapper .product img {
	transform: scale(1);
	transition: transform 1s;
}
main .recentlyadded .products .product .name, main .products .products-wrapper .product .name {
	display: block;
	color: #555555;
	padding: 20px 0 2px 0;
}
main .recentlyadded .products .product .price, main .products .products-wrapper .product .price {
	display: block;
	color: #999999;
}
main .recentlyadded .products .product .rrp, main .products .products-wrapper .product .rrp {
	color: #BBBBBB;
	text-decoration: line-through;
}
main .recentlyadded .products .product:hover img, main .products .products-wrapper .product:hover img {
	transform: scale(1.05);
	transition: transform 1s;
}
main .recentlyadded .products .product:hover .name, main .products .products-wrapper .product:hover .name {
	text-decoration: underline;
}
main > .product {
	display: flex;
	padding: 40px 0;
}
main > .product > div {
	padding-left: 15px;
}
main > .product h1 {
	font-size: 34px;
	font-weight: normal;
	margin: 0;
	padding: 20px 0 10px 0;
}
main > .product .price {
	display: block;
	font-size: 22px;
	color: #999999;
}
main > .product .rrp {
	color: #BBBBBB;
	text-decoration: line-through;
	font-size: 22px;
	padding-left: 5px;
}
main > .product form {
	display: flex;
	flex-flow: column;
	margin: 40px 0;
}
main > .product form input[type="number"] {
	width: 400px;
	padding: 10px;
	margin-bottom: 15px;
	border: 1px solid #ccc;
	color: #555555;
	border-radius: 5px;
}
main > .product form input[type="submit"] {
	background: #4e5c70;
	border: 0;
	color: #FFFFFF;
	width: 400px;
	padding: 12px 0;
	text-transform: uppercase;
	font-size: 14px;
	font-weight: bold;
	border-radius: 5px;
	cursor: pointer;
}
main > .product form input[type="submit"]:hover {
	background: #434f61;
}
main > .products h1 {
	display: block;
	font-weight: normal;
	margin: 0;
	padding: 40px 0;
	font-size: 24px;
	text-align: center;
	width: 100%;
}
main > .products .buttons {
	text-align: right;
	padding-bottom: 40px;
}
main > .products .buttons a {
	display: inline-block;
	text-decoration: none;
	margin-left: 5px;
	padding: 12px 20px;
	border: 0;
	background: #4e5c70;
	color: #FFFFFF;
	font-size: 14px;
	font-weight: bold;
	border-radius: 5px;
}
main > .products .buttons a:hover {
	background: #434f61;
}
main .cart h1 {
	display: block;
	font-weight: normal;
	margin: 0;
	padding: 40px 0;
	font-size: 24px;
	text-align: center;
	width: 100%;
}
main .cart table {
	width: 100%;
}
main .cart table thead td {
	padding: 30px 0;
	border-bottom: 1px solid #EEEEEE;
}
main .cart table thead td:last-child {
	text-align: right;
}
main .cart table tbody td {
	padding: 20px 0;
	border-bottom: 1px solid #EEEEEE;
}
main .cart table tbody td:last-child {
	text-align: right;
}
main .cart table .img {
	width: 80px;
}
main .cart table .remove {
	color: #777777;
	font-size: 12px;
	padding-top: 3px;
}
main .cart table .remove:hover {
	text-decoration: underline;
}
main .cart table .price {
	color: #999999;
}
main .cart table a {
	text-decoration: none;
	color: #555555;
}
main .cart table input[type="number"] {
	width: 68px;
	padding: 10px;
	border: 1px solid #ccc;
	color: #555555;
	border-radius: 5px;
}
main .cart .subtotal {
	text-align: right;
	padding: 40px 0;
}
main .cart .subtotal .text {
	padding-right: 40px;
	font-size: 18px;
}
main .cart .subtotal .price {
	font-size: 18px;
	color: #999999;
}
main .cart .buttons {
	text-align: right;
	padding-bottom: 40px;
}
main .cart .buttons input[type="submit"] {
	margin-left: 5px;
	padding: 12px 20px;
	border: 0;
	background: #4e5c70;
	color: #FFFFFF;
	font-size: 14px;
	font-weight: bold;
	cursor: pointer;
	border-radius: 5px;
}
main .cart .buttons input[type="submit"]:hover {
	background: #434f61;
}
main .placeorder h1 {
	display: block;
	font-weight: normal;
	margin: 0;
	padding: 40px 0;
	font-size: 24px;
	text-align: center;
	width: 100%;
}
main .placeorder p {
	text-align: center;
}
footer {
	position: absolute;
	bottom: 0;
	border-top: 1px solid #EEEEEE;
	padding: 20px 0;
	width: 100%;
}

5. MEMBUAT FILE FUNCTIONS.PHP

File functions.php berisikan function-function untuk mengatur informasi yang ditampilkan di halaman website kita yang meliputi header template, footer template, dan fungsi koneksi database. Berikut kodenya dan simpan dengan nama functions.php



	
		
		$title
		
		
	
	
        

Shopping Cart System

EOT; } // Template footer function template_footer() { $year = date('Y'); echo <<

© $year, Shopping Cart System

EOT; } ?>

6. MEMBUAT FILE INDEX.PHP

File index.php pada dasarnya akan menjadi file utama kita untuk mengakses semua halaman kita. Kita akan menggunakan routing dan menggunakan permintaan GET untuk menentukan halaman mana yang akan ditampikan seusai dengan action dari pengunjung.

Berikut kodenya dan simpan dengan nama index.php


7. MEMBUAT FILE HOME.PHP

Halaman Home akan menjadi halaman pertama yang akan dilihat pelanggan kita. Untuk halaman ini, kita dapat menambahkan gambar dan teks unggulan, bersama dengan daftar 4 produk yang baru saja ditambahkan.

Berikut kodenya dan simpan dengan nama home.php

prepare('SELECT * FROM products ORDER BY date_added DESC LIMIT 4');
$stmt->execute();
$recently_added_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>




Recently Added Products

8. MEMBUAT FILE PRODUCTS.PHP

Halaman produk akan menjadi tempat pelanggan kami akan pergi untuk menelusuri semua produk kiat. Kita akan membatasi jumlah produk yang ditampilkan di setiap halaman dan menambahkan pagination yang memungkinkan pelanggan untuk menavigasi antar halaman.

Berikut kodenya dan simpan dengan nama products.php

prepare('SELECT * FROM products ORDER BY date_added DESC LIMIT ?,?');
// bindValue will allow us to use integer in the SQL statement, we need to use for LIMIT
$stmt->bindValue(1, ($current_page - 1) * $num_products_on_each_page, PDO::PARAM_INT);
$stmt->bindValue(2, $num_products_on_each_page, PDO::PARAM_INT);
$stmt->execute();
// Fetch the products from the database and return the result as an Array
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get the total number of products
$total_products = $pdo->query('SELECT * FROM products')->rowCount();
?>



Products

Products

1): ?> Prev ($current_page * $num_products_on_each_page) - $num_products_on_each_page + count($products)): ?> Next

9. PEMBUATAN FILE PRODUCT.PHP

Halaman produk akan menampilkan semua detail untuk produk tertentu, ditentukan oleh variabel GET request ID. Pelanggan dapat melihat harga, gambar, dan deskripsi. Pelanggan akan dapat mengubah jumlah dan menambahkan ke keranjang dengan mengklik tombol.

Kodenya sebagaiberikut dan simpan dengan nama product.php

prepare('SELECT * FROM products WHERE id = ?');
    $stmt->execute([$_GET['id']]);
    // Fetch the product from the database and return the result as an Array
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    // Check if the product exists (array is not empty)
    if (!$product) {
        // Simple error to display if the id for the product doesn't exists (array is empty)
        exit('Product does not exist!');
    }
} else {
    // Simple error to display if the id wasn't specified
    exit('Product does not exist!');
}
?>



">

$ 0): ?> $

10. MEMBUAT HALAMAN SHOPPING CART / CART.PHP

Halaman shoppingcart adalah tempat pelanggan dapat melihat daftar produk mereka yang ditambahkan ke keranjang belanja. Mereka akan memiliki kemampuan untuk menghapus produk dan memperbarui jumlahnya.

berikut kodenganya simpan dengan nama cart.php

prepare('SELECT * FROM products WHERE id = ?');
    $stmt->execute([$_POST['product_id']]);
    // Fetch the product from the database and return the result as an Array
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    // Check if the product exists (array is not empty)
    if ($product && $quantity > 0) {
        // Product exists in database, now we can create/update the session variable for the cart
        if (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) {
            if (array_key_exists($product_id, $_SESSION['cart'])) {
                // Product exists in cart so just update the quanity
                $_SESSION['cart'][$product_id] += $quantity;
            } else {
                // Product is not in cart so add it
                $_SESSION['cart'][$product_id] = $quantity;
            }
        } else {
            // There are no products in cart, this will add the first product to cart
            $_SESSION['cart'] = array($product_id => $quantity);
        }
    }
    // Prevent form resubmission...
    header('location: index.php?page=cart');
    exit;
}




// Remove product from cart, check for the URL param "remove", this is the product id, make sure it's a number and check if it's in the cart
if (isset($_GET['remove']) && is_numeric($_GET['remove']) && isset($_SESSION['cart']) && isset($_SESSION['cart'][$_GET['remove']])) {
    // Remove the product from the shopping cart
    unset($_SESSION['cart'][$_GET['remove']]);
}



// Update product quantities in cart if the user clicks the "Update" button on the shopping cart page
if (isset($_POST['update']) && isset($_SESSION['cart'])) {
    // Loop through the post data so we can update the quantities for every product in cart
    foreach ($_POST as $k => $v) {
        if (strpos($k, 'quantity') !== false && is_numeric($v)) {
            $id = str_replace('quantity-', '', $k);
            $quantity = (int)$v;
            // Always do checks and validation
            if (is_numeric($id) && isset($_SESSION['cart'][$id]) && $quantity > 0) {
                // Update new quantity
                $_SESSION['cart'][$id] = $quantity;
            }
        }
    }
    // Prevent form resubmission...
    header('location: index.php?page=cart');
    exit;
}



// Send the user to the place order page if they click the Place Order button, also the cart should not be empty
if (isset($_POST['placeorder']) && isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
    header('Location: index.php?page=placeorder');
    exit;
}



// Check the session variable for products in cart
$products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : array();
$products = array();
$subtotal = 0.00;
// If there are products in cart
if ($products_in_cart) {
    // There are products in the cart so we need to select those products from the database
    // Products in cart array to question mark string array, we need the SQL statement to include IN (?,?,?,...etc)
    $array_to_question_marks = implode(',', array_fill(0, count($products_in_cart), '?'));
    $stmt = $pdo->prepare('SELECT * FROM products WHERE id IN (' . $array_to_question_marks . ')');
    // We only need the array keys, not the values, the keys are the id's of the products
    $stmt->execute(array_keys($products_in_cart));
    // Fetch the products from the database and return the result as an Array
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // Calculate the subtotal
    foreach ($products as $product) {
        $subtotal += (float)$product['price'] * (int)$products_in_cart[$product['id']];
    }
}
?>




Shopping Cart

Product Price Quantity Total
You have no products added in your Shopping Cart
">
Remove
$ $
Subtotal $

11. MEMBUAT HALAMAN PLACE ORDER / PLACEORDER.PHP

Halaman ini berguna untuk mengarahkan konsumen jika menekan tombol place order

berikut kodenya simpan dengan nama placeorder.php



Your Order Has Been Placed

Thank you for ordering with us, we'll contact you by email with your order details.

12. PENUTUP

Selamat! Anda sudah berhasil membuat sistem shopping cart dengan PHP dan MySQL, ini hanyalah sistem SHOPPING CART dasar tempat Anda bekerja, oleh karena itu saya tidak menyarankan untuk melanjutkan produksi sampai Anda membuat sejumlah perubahan dan penambahan yang wajar, Anda perlu menambahkan penanganan kesalahan Anda sendiri, metode pembayaran, dan validasi.