Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 23, 2023 02:00
Show Gist options
  • Save code-boxx/03445894dc41f7089d392c6689b864d1 to your computer and use it in GitHub Desktop.
Save code-boxx/03445894dc41f7089d392c6689b864d1 to your computer and use it in GitHub Desktop.
PHP eCommerce Website

SIMPLE PHP MYSQL ECOMMERCE WEBSITE

https://code-boxx.com/simple-ecommerce-website-php/

IMAGES

img-a img-b img-c img-d

NOTES

  1. Access 2-shop.html in the browser, Captain Obvious to the rescue – Use http:// not file://.
  2. Set your own products in 1-lib.php.
  3. Complete your own checkout sequence in 1-lib.php and 3-shop.js.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
if (isset($_POST["req"])) {
// (A) PRODUCTS LIST
$products = [
1 => [
"n" => "Laptop",
"p" => 345.67,
"i" => "img-a.png"
],
2 => [
"n" => "Smartphone",
"p" => 123.45,
"i" => "img-b.png"
],
3 => [
"n" => "Tablet",
"p" => 234.56,
"i" => "img-c.png"
],
4 => [
"n" => "Headphones",
"p" => 34.56,
"i" => "img-d.png"
]
];
// (B) HANDLE REQUESTS
switch ($_POST["req"]) {
// (B1) INVALID REQUEST
default: echo "Invalid request"; break;
// (B2) GET PRODUCTS
case "get":
echo json_encode($products);
break;
// (B3) CHECKOUT
case "checkout":
// (B3-1) DATA YOGA
$cart = json_decode($_POST["cart"], true);
unset($_POST["req"]);
unset($_POST["cart"]);
// (B3-2) SEND VIA EMAIL
$msg = "";
foreach ($_POST as $k=>$v) { $msg .= "$k : $v\r\n"; }
foreach ($cart as $i=>$q) {
$msg .= sprintf("%u X %s - $%s\r\n",
$q, $products[$i]["n"], $q * $products[$i]["p"]
);
}
echo mail("[email protected]", "Order Received", $msg)
? "OK" : "Failed to send email";
break;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Simple PHP eCommerce</title>
<meta charset="utf-8">
<link rel="stylesheet" href="3-shop.css">
<script src="3-shop.js"></script>
</head>
<body>
<!-- (A) PRODUCTS + SHOPPING CART -->
<div id="wrap">
<!-- (A1) HEADER -->
<div id="head">
<div id="iCart">
My Cart <span id="cCart">0</span>
</div>
<div id="iDummy">My Account</div>
</div>
<!-- (A2) PRODUCTS -->
<div id="products"></div>
<!-- (A3) CART ITEMS -->
<div id="wCart">
<span id="wCartClose" class="button" onclick="document.getElementById('wCart').classList.remove('show')">&#8678;</span>
<h2>SHOPPING CART</h2>
<div id="cart"></div>
</div>
</div>
<!-- (B) CHECKOUT FORM -->
<div id="checkout"><form onsubmit="return shop.checkout()">
<div id="cgClose" class="button" onclick="shop.togcf(false)">X</div>
<label>Name</label>
<input type="text" name="name" required value="Jon Doe">
<label>Email</label>
<input type="email" name="email" required value="[email protected]">
<input class="button" type="submit" value="Checkout">
</form></div>
</body>
</html>
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
padding: 0;
max-width: 1000px;
margin: 0 auto;
background: #ebebeb;
}
.button {
padding: 10px;
border: 0;
font-weight: 700;
color: #fff;
background: #b90909;
cursor: pointer;
}
/* (B) PRODUCTS + CART */
/* (B1) WRAPPER */
#wrap { position: relative; }
/* (B2) HEADER */
#head {
display: flex;
flex-direction: row-reverse;
align-items: center;
padding: 20px 10px;
font-size: 16px;
color: #fff;
background: #282828;
}
#iDummy, #iCart {
margin: 0 10px;
cursor: pointer;
}
#cCart {
font-weight: 700;
padding: 5px;
margin-left: 5px;
background: #951818;
}
/* (B3) PRODUCTS WRAPPER */
#products {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-gap: 10px; padding: 20px;
}
@media screen and (max-width:600px) {
#products { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
/* (B4) PRODUCTS */
.pCell { background: #fff; }
.pImg { width: 100%; }
.pDetails { padding: 10px; }
.pName, .pPrice { margin: 5px 0; }
.pName { font-size: 1.3rem; }
.pPrice { font-size: 0.9rem; color: #686868; }
.pAdd { width: 100%; }
/* (B5) CART WRAPPER */
#wCart {
display: none;
position: absolute;
top: 0; left: 0; z-index: 999;
width: 280px; padding: 10px;
height: 100%; min-height: 100vh;
background: #f5f5f5;
border-right: 1px solid #a7a7a7;
border-left: 1px solid #a7a7a7;
}
#wCart.show { display: block; }
#wCartClose {
font-size: 20px;
background: #282828;
}
/* (B6) CART ITEMS */
.cCell {
display: flex;
align-items: stretch;
margin-bottom: 15px;
border: 1px solid #e3e3e3;
background: #fff;
}
.cCell.empty { padding: 10px; }
.cQty {
text-align: center;
width: 50px;
border: 0;
background: #e7e7e7;
}
.cInfo {
flex-grow: 1;
padding: 10px 5px;
}
.cName { font-weight: 700; }
.cPrice { font-size: 0.9rem; }
/* (C) CHECKOUT */
#checkout {
position: fixed;
top: 0; left: 0; z-index: 999;
width: 100vw; height: 100vh;
background: rgba(0, 0, 0, 0.8);
display: none;
align-items: center;
justify-content: center;
}
#checkout.show { display: flex; }
#checkout form {
position: relative;
width: 400px;
padding: 20px;
background: #fff;
}
#checkout label, #checkout input {
display: block;
width: 100%;
}
#checkout label { padding: 10px 0; }
#checkout input { padding: 10px; }
#checkout input[type=submit] { margin-top: 20px; }
#cgClose {
position: absolute;
top: 0; right: 0;
}
var shop = {
// (A) HELPER - AJAX FETCH
fetch : (data, after) => {
// (A1) FORM DATA
let form;
if (data instanceof FormData) { form = data; }
else {
form = new FormData();
for (let [k, v] of Object.entries(data)) { form.append(k, v); }
}
// (A2) FETCH
fetch("1-lib.php", { method : "post", body : form })
.then(res => res.text())
.then(txt => after(txt))
.catch(err => console.error(err));
},
// (B) PROPERTIES
hPdt : null, // html products
hCart : null, // html cart
hCCart : null, // html cart count
hCO : null, // html checkout wrapper
hCOF : null, // html checkout form
products : null, // products list
cart : null, // cart items
qty : 0, // cart total item quantity
total : 0, // cart total amount
// (C) INITIALIZE
init : () => {
// (C1) GET HTML ELEMENTS
shop.hPdt = document.getElementById("products");
shop.hCart = document.getElementById("cart");
shop.hCCart = document.getElementById("cCart");
shop.hCO = document.getElementById("checkout");
shop.hCOF = document.querySelector("#checkout form");
// (C2) CLICK TO TOGGLE CART
document.getElementById("iCart").onclick = () => {
document.getElementById("wCart").classList.toggle("show");
};
// (C3) RESTORE CART
shop.cart = localStorage.getItem("cart");
if (shop.cart == null) { shop.cart = {}; }
else { shop.cart = JSON.parse(shop.cart); }
// (C4) LOAD PRODUCTS > DRAW HTML
shop.fetch({"req": "get"}, data => {
// (C4-1) PARSE DATA INTO JS OBJECT
shop.products = JSON.parse(data);
// (C4-2) DRAW HTML PRODUCTS
for (let [id, pdt] of Object.entries(shop.products)) {
let row = document.createElement("div");
row.className = "pCell";
row.innerHTML = `<img class="pImg" src="${pdt.i}">
<div class="pDetails">
<div class="pName">${pdt.n}</div>
<div class="pPrice">$${pdt.p.toFixed(2)}</div>
<input class="pAdd button" type="button" value="Add To Cart" onclick="shop.add(${id})">
</div>`;
shop.hPdt.appendChild(row);
}
// (C4-3) DRAW CART ITEMS
shop.drawcart();
});
},
// (D) SAVE CART ITEMS INTO LOCALSTORAGE
save : () => localStorage.setItem("cart", JSON.stringify(shop.cart)),
// (E) DRAW CART ITEMS
drawcart : () => {
// (E1) RESET
let row;
shop.qty = 0;
shop.total = 0;
shop.hCart.innerHTML = "";
// (E2) EMPTY CART
if (Object.keys(shop.cart).length==0) {
row = document.createElement("div");
row.className = "cCell empty";
row.innerHTML = `Cart is empty`;
shop.hCart.appendChild(row);
shop.hCCart.innerHTML = 0;
}
// (E3) DRAW ITEMS
else {
for (let [i, q] of Object.entries(shop.cart)) {
// (E3-1) CALCULATE SUBTOTAL
let subtotal = q * shop.products[i]["p"];
shop.total += subtotal;
shop.qty += parseInt(q);
// (E3-2) ITEM ROW
row = document.createElement("div");
row.className = "cCell";
row.innerHTML = `<input class="cQty" type="number" value="${q}"
min="0" max="99" onchange="shop.change(${i}, this.value)">
<div class="cInfo">
<div class="cName">${shop.products[i]["n"]}</div>
<div class="cPrice">$${subtotal.toFixed(2)}</div>
</div>
<input class="cDel button" type="button" value="X" onclick="shop.remove(${i})">`;
shop.hCart.appendChild(row);
}
// (E3-3) CART TOTAL
row = document.createElement("div");
row.className = "cCell";
row.innerHTML = `<input class="cDel button" type="button" value="X" onclick="shop.empty()">
<div class="cInfo">
<div class="cName">Total</div>
<div class="cPrice">$${shop.total.toFixed(2)}</div>
</div>
<input class="cDel button" type="button" value="&gt;" onclick="shop.togcf(true)">`;
shop.hCart.appendChild(row);
// (E3-4) TOTAL QUANTITY
shop.hCCart.innerHTML = shop.qty;
}
},
// (F) ADD PRODUCT TO CART
add : id => {
if (shop.cart[id]==undefined) { shop.cart[id] = 1; }
else { shop.cart[id]++; }
shop.save(); shop.drawcart();
},
// (G) CHANGE QUANTITY IN CART
change : (id, qty) => {
if (qty <= 0) { shop.remove(id) }
else { shop.cart[id] = qty; }
shop.save(); shop.drawcart();
},
// (H) REMOVE PRODUCT FROM CART
remove : id => {
delete shop.cart[id];
shop.save(); shop.drawcart();
},
// (I) EMPTY CART
empty : () => { if (confirm("Empty cart?")) {
shop.cart = {};
shop.save(); shop.drawcart();
}},
// (J) TOGGLE CHECKOUT FORM
togcf : show => {
if (show) { shop.hCO.className = "show"; }
else { shop.hCO.className = ""; }
},
// (K) CHECKOUT
checkout : () => {
// (K1) FORM DATA
let form = new FormData(shop.hCOF);
form.append("req", "checkout");
form.append("cart", JSON.stringify(shop.cart));
// (K2) AJAX PROCESS
shop.fetch(form, res => {
if (res=="OK") {
shop.cart = {};
shop.save();
shop.drawcart();
shop.togcf(false);
alert("CHECKOUT OK. DO SOMETHING - REDIRECT TO THANK YOU?");
} else { alert(res); }
});
// (K3) PREVENT FORM SUBMIT
return false;
}
};
window.onload = shop.init;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment