By GokiSoft.com|
08:37 19/05/2021|
Học PHP
[Full Source Code] Xây dựng web hoàn thiện gồm cart page + checkout page + complete page - Lập trình PHP/MySQL
#guideline.txt
B1. Tao database
create database bt2290
create table products (
id int primary key auto_increment,
title varchar(250),
thumbnail varchar(500),
content longtext,
price float,
created_at datetime,
updated_at datetime
);
create table orders (
id int primary key auto_increment,
fullname varchar(100),
phone_number varchar(20),
email varchar(150),
address varchar(200),
order_date datetime
);
create table order_details (
id int primary key auto_increment,
order_id int references orders (id),
product_id int references products (id),
num int,
price float
)
B2. Xay dung cau truc du an
- db
- config.php
- dbhelper.php
- utils
- utility.php
B3. Fake data -> DONE
B4. Phat trien cac chuc nang cua du an
1) products.php -> OK
2) details.php -> OK
3) cart.php
Giai phap -> cookie: thoi gian luu lau -> phu thuoc vao thoi gian set
-> id san pham + so luong
cart: [
{
"id": 1,
"num": 3
},{
"id": 2,
"num": 1
},
]
-> session: thoi gian luu cart rat ngan
#config.php
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'bt2290');
#dbhelper.php
<?php
require_once('config.php');
/**
* Su dung cho cac lenh: insert, update, delete
*/
function execute($sql) {
//Mo ket noi toi database
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
mysqli_set_charset($conn, 'utf8');
//query
mysqli_query($conn, $sql);
//Dong ket noi
mysqli_close($conn);
}
/**
* Su dung cho cac lenh: select
*/
function executeResult($sql, $onlyOne = false) {
//Mo ket noi toi database
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
mysqli_set_charset($conn, 'utf8');
//query
$resultset = mysqli_query($conn, $sql);
if($onlyOne) {
$data = mysqli_fetch_array($resultset, 1);
} else {
$data = [];
while(($row = mysqli_fetch_array($resultset, 1)) != null) {
$data[] = $row;
}
}
//Dong ket noi
mysqli_close($conn);
return $data;
}
#utility.php
<?php
function removeSpecialCharacter($str) {
$str = str_replace('\\', '\\\\', $str);
$str = str_replace('\'', '\\\'', $str);
return $str;
}
function getPost($key) {
$value = '';
if(isset($_POST[$key])) {
$value = $_POST[$key];
}
return removeSpecialCharacter($value);
}
function getGet($key) {
$value = '';
if(isset($_GET[$key])) {
$value = $_GET[$key];
}
return removeSpecialCharacter($value);
}
#checkout-form.php
<?php
if(!empty($_POST)) {
$cart = [];
if(isset($_COOKIE['cart'])) {
$json = $_COOKIE['cart'];
$cart = json_decode($json, true);
}
if($cart ==null || count($cart) == 0) {
header('Location: products.php');
die();
}
$fullname = getPost('fullname');
$email = getPost('email');
$phone_number = getPost('phone_number');
$address = getPost('address');
$orderDate = date('Y-m-d H:i:s');
//add order
$sql = "insert into orders(fullname, email, phone_number, address, order_date) values ('$fullname', '$email', '$phone_number', '$address', '$orderDate')";
execute($sql);
$sql = "select * from orders where order_date = '$orderDate'";
$order = executeResult($sql, true);
$orderId = $order['id'];
$idList = [];
foreach ($cart as $item) {
$idList[] = $item['id'];
}
if(count($idList) > 0) {
$idList = implode(',', $idList);
//[2, 5, 6] => 2,5,6
$sql = "select * from products where id in ($idList)";
$cartList = executeResult($sql);
} else {
$cartList = [];
}
foreach ($cartList as $item) {
$num = 0;
foreach ($cart as $value) {
if($value['id'] == $item['id']) {
$num = $value['num'];
break;
}
}
$sql = "insert into order_details(order_id, product_id, num, price) values ($orderId, ".$item['id'].", $num, ".$item['price'].")";
execute($sql);
}
header('Location: complete.php');
setcookie('cart', '[]', time()-1000, '/');
}
#cookie.php
<?php
require_once('../utils/utility.php');
if(!empty($_POST)) {
$action = getPost('action');
$id = getPost('id');
$num = getPost('num');
$cart = [];
if(isset($_COOKIE['cart'])) {
$json = $_COOKIE['cart'];
$cart = json_decode($json, true);
}
switch ($action) {
case 'add':
$isFind = false;
for ($i=0; $i < count($cart); $i++) {
if($cart[$i]['id'] == $id) {
$cart[$i]['num'] += $num;
$isFind = true;
break;
}
}
if(!$isFind) {
$cart[] = [
'id'=>$id,
'num'=>$num
];
}
setcookie('cart', json_encode($cart), time() + 30*24*60*60, '/');
break;
case 'delete':
for ($i=0; $i < count($cart); $i++) {
if($cart[$i]['id'] == $id) {
array_splice($cart, $i, 1);
break;
}
}
setcookie('cart', json_encode($cart), time() + 30*24*60*60, '/');
break;
}
}
#footer.php
<!-- footer -->
<footer style="background-color: black; color: white; padding: 15px;">
<h5 style="text-align: center;">Copyright © 2019 All rights reserved</h5>
</footer>
</body>
</html>
#header.php
<!DOCTYPE html>
<html>
<head>
<title>Products Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="all,follow">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style type="text/css">
.container .row {
min-height: 1000px;
}
</style>
</head>
<body>
<!-- header -->
<!-- Grey with black text -->
<nav class="navbar navbar-expand-sm bg-primary navbar-dark">
<div class="container">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="products.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.php">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Track Order</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<?php
$cart = [];
if(isset($_COOKIE['cart'])) {
$json = $_COOKIE['cart'];
$cart = json_decode($json, true);
}
$count = 0;
foreach ($cart as $item) {
$count += $item['num'];
}
?>
<a href="cart.php">
<button type="button" class="btn btn-primary">
Cart <span class="badge badge-light"><?=$count?></span>
</button>
</a>
</div>
</nav>
#cart.php
<?php
require_once('db/dbhelper.php');
require_once('utils/utility.php');
include_once('layouts/header.php');
$cart = [];
if(isset($_COOKIE['cart'])) {
$json = $_COOKIE['cart'];
$cart = json_decode($json, true);
}
$idList = [];
foreach ($cart as $item) {
$idList[] = $item['id'];
}
if(count($idList) > 0) {
$idList = implode(',', $idList);
//[2, 5, 6] => 2,5,6
$sql = "select * from products where id in ($idList)";
$cartList = executeResult($sql);
} else {
$cartList = [];
}
?>
<!-- body -->
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>No</th>
<th>Thumbnail</th>
<th>Title</th>
<th>Num</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$count = 0;
$total = 0;
foreach ($cartList as $item) {
$num = 0;
foreach ($cart as $value) {
if($value['id'] == $item['id']) {
$num = $value['num'];
break;
}
}
$total += $num*$item['price'];
echo '
<tr>
<td>'.(++$count).'</td>
<td><img src="'.$item['thumbnail'].'" style="height: 100px"/></td>
<td>'.$item['title'].'</td>
<td>'.$num.'</td>
<td>'.number_format($item['price'], 0, ',', '.').'</td>
<td>'.number_format($num*$item['price'], 0, ',', '.').'</td>
<td><button class="btn btn-danger" onclick="deleteCart('.$item['id'].')">Delete</button></td>
</tr>';
}
?>
</tbody>
</table>
<p style="font-size: 30px; color: red">
Total: <?=number_format($total, 0, ',', '.')?>
</p>
<a href="checkout.php">
<button class="btn btn-success" style="width: 100%; font-size: 32px;">Checkout</button>
</a>
</div>
</div>
</div>
<script type="text/javascript">
function deleteCart(id) {
$.post('api/cookie.php', {
'action': 'delete',
'id': id
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#checkout.php
<?php
require_once('db/dbhelper.php');
require_once('utils/utility.php');
include_once('layouts/header.php');
require_once('api/checkout-form.php');
$cart = [];
if(isset($_COOKIE['cart'])) {
$json = $_COOKIE['cart'];
$cart = json_decode($json, true);
}
$idList = [];
foreach ($cart as $item) {
$idList[] = $item['id'];
}
if(count($idList) > 0) {
$idList = implode(',', $idList);
//[2, 5, 6] => 2,5,6
$sql = "select * from products where id in ($idList)";
$cartList = executeResult($sql);
} else {
$cartList = [];
}
?>
<!-- body -->
<form method="post">
<div class="container">
<div class="row">
<div class="col-md-5">
<h3>Shipping Information</h3>
<div class="form-group">
<label for="usr">Name:</label>
<input required="true" type="text" class="form-control" id="usr" name="fullname">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input required="true" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="phone_number">Phone Number:</label>
<input type="text" class="form-control" id="phone_number" name="phone_number">
</div>
<div class="form-group">
<label for="address">Address:</label>
<input type="text" class="form-control" id="address" name="address">
</div>
<div class="form-group">
<label for="note">Note:</label>
<textarea class="form-control" rows="3" name="note" id="note"></textarea>
</div>
</div>
<div class="col-md-7">
<h3>Cart</h3>
<table class="table table-bordered table-responsive">
<thead>
<tr>
<th>No</th>
<th>Num</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php
$count = 0;
$total = 0;
foreach ($cartList as $item) {
$num = 0;
foreach ($cart as $value) {
if($value['id'] == $item['id']) {
$num = $value['num'];
break;
}
}
$total += $num*$item['price'];
echo '
<tr>
<td>'.(++$count).'</td>
<td>'.$item['title'].'</td>
<td>'.$num.'</td>
<td>'.number_format($item['price'], 0, ',', '.').'</td>
<td>'.number_format($num*$item['price'], 0, ',', '.').'</td>
</tr>';
}
?>
</tbody>
</table>
<p style="font-size: 30px; color: red">
Total: <?=number_format($total, 0, ',', '.')?>
</p>
<button class="btn btn-success" style="width: 100%; font-size: 32px;">Complete</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
function deleteCart(id) {
$.post('api/cookie.php', {
'action': 'delete',
'id': id
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#complete.php
<?php
include_once('layouts/header.php');
?>
<!-- body -->
<div class="container">
<div class="row">
<h1 style="text-align: center; color: red">Complete Checkout</h1>
</div>
</div>
<?php
include_once('layouts/footer.php');
?>
#details.php
<?php
require_once('db/dbhelper.php');
require_once('utils/utility.php');
include_once('layouts/header.php');
$id = getGet('id');
$product = executeResult('select * from products where id = '.$id, true);
if($product == null) {
header('Location: products.php');
die();
}
?>
<!-- body -->
<div class="container">
<div class="row">
<div class="col-md-5">
<img style="width: 100%" src="<?=$product['thumbnail']?>">
</div>
<div class="col-md-7">
<h4><?=$product['title']?></h4>
<p style="font-size: 36px; color: red"><?=number_format($product['price'], 0, ',', '.')?></p>
<button class="btn btn-success" style="width: 100%; font-size: 30px;" onclick="addToCart(<?=$id?>)">Add to cart</button>
</div>
<div class="col-md-12">
<?=$product['content']?>
<!-- duplicate -> code for fun -->
<?=$product['content']?>
<?=$product['content']?>
<?=$product['content']?>
<?=$product['content']?>
</div>
</div>
</div>
<script type="text/javascript">
function addToCart(id) {
$.post('api/cookie.php', {
'action': 'add',
'id': id,
'num': 1
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#products.php
<?php
require_once('db/dbhelper.php');
require_once('utils/utility.php');
include_once('layouts/header.php');
$productList = executeResult('select * from products');
?>
<!-- body -->
<div class="container">
<div class="row">
<?php
foreach ($productList as $item) {
echo '<div class="col-md-3 col-6">
<a href="details.php?id='.$item['id'].'"><img src="'.$item['thumbnail'].'" style="width: 100%"></a>
<a href="details.php?id='.$item['id'].'"><p>'.$item['title'].'</p></a>
<p style="color: red">'.number_format($item['price'], 0, ',', '.').'đ</p>
</div>';
}
?>
</div>
</div>
<?php
include_once('layouts/footer.php');
?>
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)