By GokiSoft.com|
08:39 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 - Sử dụng session - Lập trình PHP/MySQL
#readme.txt
B1. Tạo database (CSDL)
- create database BT2290
create table products (
id int primary key auto_increment,
title varchar(250) not null,
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(200),
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. Fake data -> DONE
B3. Xay khung du an
- db:
- config.php
- dbhelper.php
- utils
- utility.php
B4. Phát triển các chức năng của dự án
1) products.php
2) detail.php
3) cart.php
Yeu cau: add to cart -> cart -> quan ly dc san pham + so luong trong cart do la nhu the nao
Giai phap: Session
$_SESSION['cart'] => [
[
object product,
'num' => ???
],
[
object product,
'num' => ???
]
]
Phuong phap lam nhu the nao???
4) checkout.php
5) complete.php -> sau khi hoàn thành thanh toán.
#cart.php
<?php
session_start();
$title = 'Cart Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');
require_once('utils/utility.php');
?>
<!-- body START -->
<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>Price</th>
<th>Num</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
// var_dump($cart);die();
$count = 0;
$total = 0;
foreach ($cart as $item) {
$total += $item['num'] * $item['price'];
echo '
<tr>
<td>'.(++$count).'</td>
<td><img src="'.$item['thumbnail'].'" style="width: 100px"></td>
<td>'.$item['title'].'</td>
<td>'.number_format($item['price'], 0, '', '.').' VND</td>
<td>'.$item['num'].'</td>
<td>'.number_format($item['num'] * $item['price'], 0, '', '.').' VND</td>
<td><button class="btn btn-danger" onclick="deleteItem('.$item['id'].')">Delete</button></td>
</tr>';
}
?>
</tbody>
</table>
<p style="font-size: 26px; color: red">
<?=number_format($total, 0, '', '.')?> VND
</p>
<a href="checkout.php">
<button class="btn btn-success" style="width: 100%; font-size: 30px;">Continue</button>
</a>
</div>
</div>
<!-- body END -->
<script type="text/javascript">
function deleteItem(id) {
$.post('api/api-product.php', {
'action': 'delete',
'id': id
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#complete.php
<?php
session_start();
$title = 'Complete Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');
require_once('utils/utility.php');
?>
<!-- body START -->
<div class="row">
<div class="col-md-12">
<h1 style="text-align: center;">Complete Checkout</h1>
</div>
</div>
<!-- body END -->
<?php
include_once('layouts/footer.php');
?>
#checkout.php
<?php
session_start();
$title = 'Checkout Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');
require_once('utils/utility.php');
require_once('api/form-checkout.php');
?>
<!-- body START -->
<form method="post">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label for="usr">FullName <font color="red">*</font>:</label>
<input required="true" type="text" class="form-control" id="fullname" name="fullname">
</div>
<div class="form-group">
<label for="email">Email <font color="red">*</font>:</label>
<input required="true" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="phone_number">Phone Number <font color="red">*</font>:</label>
<input required="true" type="tel" class="form-control" id="phone_number" name="phone_number">
</div>
<div class="form-group">
<label for="address">Address <font color="red">*</font>:</label>
<input required="true" type="text" class="form-control" id="address" name="address">
</div>
</div>
<div class="col-md-7">
<table class="table table-bordered">
<thead>
<tr>
<th>No</th>
<th>Thumbnail</th>
<th>Title</th>
<th>Price</th>
<th>Num</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
// var_dump($cart);die();
$count = 0;
$total = 0;
foreach ($cart as $item) {
$total += $item['num'] * $item['price'];
echo '
<tr>
<td>'.(++$count).'</td>
<td><img src="'.$item['thumbnail'].'" style="width: 100px"></td>
<td>'.$item['title'].'</td>
<td>'.number_format($item['price'], 0, '', '.').' VND</td>
<td>'.$item['num'].'</td>
<td>'.number_format($item['num'] * $item['price'], 0, '', '.').' VND</td>
</tr>';
}
?>
</tbody>
</table>
<p style="font-size: 26px; color: red">
<?=number_format($total, 0, '', '.')?> VND
</p>
<button class="btn btn-success" style="width: 100%; font-size: 30px;">Complete</button>
</div>
</div>
</form>
<!-- body END -->
<?php
include_once('layouts/footer.php');
?>
#detail.php
<?php
session_start();
$title = 'Detail Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');
require_once('utils/utility.php');
$id = getGet('id');
$product = executeResult('select * from products where id = '.$id, true);
?>
<!-- body START -->
<div class="row">
<div class="col-md-5">
<img src="<?=$product['thumbnail']?>" style="width: 100%">
</div>
<div class="col-md-7">
<p style="font-size: 26px;"><?=$product['title']?></p>
<p style="font-size: 26px; color: red"><?=number_format($product['price'], 0, '', '.')?> VND</p>
<button class="btn btn-success" onclick="addToCart(<?=$id?>)" style="width: 100%; font-size: 26px;">Add to cart</button>
<a href="checkout.php">
<button class="btn btn-danger" style="width: 100%; font-size: 26px; margin-top: 10px;">Checkout</button>
</a>
</div>
<div class="col-md-12">
<?=$product['content']?>
</div>
</div>
<!-- body END -->
<script type="text/javascript">
function addToCart(id) {
$.post('api/api-product.php', {
'action': 'add',
'id': id
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#products.php
<?php
session_start();
$title = 'Product Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');
require_once('utils/utility.php');
$productList = executeResult('select * from products');
?>
<!-- body START -->
<div class="row">
<?php
foreach ($productList as $item) {
echo '<div class="col-md-3" style="border: solid 2px #e9e6e6; margin-top: 10px;">
<a href="detail.php?id='.$item['id'].'"><img src="'.$item['thumbnail'].'" style="width: 100%"></a>
<a href="detail.php?id='.$item['id'].'"><p style="font-size: 26px;">'.$item['title'].'</p></a>
<p style="font-size: 26px; color: red">'.number_format($item['price'], 0, '', '.').' VND</p>
</div>';
}
?>
</div>
<!-- body END -->
<?php
include_once('layouts/footer.php');
?>
#api-product.php
<?php
session_start();
if(!empty($_POST)) {
require_once('../db/dbhelper.php');
require_once('../utils/utility.php');
$action = getPost('action');
$id = getPost('id');
switch ($action) {
case 'add':
addToCart($id);
break;
case 'delete':
deleteItem($id);
break;
}
}
function deleteItem($id) {
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
for ($i=0; $i < count($cart); $i++) {
if($cart[$i]['id'] == $id) {
array_splice($cart, $i, 1);
break;
}
}
//update session
$_SESSION['cart'] = $cart;
}
function addToCart($id) {
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
$isFind = false;
for ($i=0; $i < count($cart); $i++) {
if($cart[$i]['id'] == $id) {
$cart[$i]['num']++;
$isFind = true;
break;
}
}
if(!$isFind) {
$product = executeResult('select * from products where id = '.$id, true);
$product['num'] = 1;
$cart[] = $product;
}
//update session
$_SESSION['cart'] = $cart;
}
#form-checkout.php
<?php
if(!empty($_POST)) {
$fullname = getPost('fullname');
$address = getPost('address');
$email = getPost('email');
$phone_number = getPost('phone_number');
$order_date = date('Y-m-d H:i:s');
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
if($cart == null || count($cart) == 0) {
header('Location: products.php');
die();
}
$sql = "insert into orders (fullname, address, email, phone_number, order_date) values ('$fullname', '$address', '$email', '$phone_number', '$order_date')";
execute($sql);
$sql = "select * from orders where order_date = '$order_date'";
$order = executeResult($sql, true);
$orderId = $order['id'];
foreach ($cart as $item) {
$product_id = $item['id'];
$num = $item['num'];
$price = $item['price'];
$sql = "insert into order_details(order_id, product_id, num, price) values ($orderId, $product_id, $num, $price)";
execute($sql);
}
// session_destroy();
unset($_SESSION['cart']);
header('Location: complete.php');
die();
}
#footer.php
</div>
<!-- Footer -->
<footer style="background-color: black; color: white; padding: 10px;">
<h4 style="text-align: center;">Copyright © 2019 All rights reserved</h4>
</footer>
</body>
</html>
#header.php
<!DOCTYPE html>
<html>
<head>
<title><?=$title?></title>
<!-- 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">
.main {
min-height: 700px;
}
</style>
</head>
<body>
<!-- header START -->
<!-- Grey with black text -->
<nav class="navbar navbar-expand-sm bg-primary navbar-dark">
<div class="container" style="padding: 0px !important;">
<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="#">About</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 Us</a>
</li>
</ul>
<?php
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
$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>
<!-- header END -->
<div class="container main">
#config.php
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'bt2290');
#dbhelper.php
<?php
require_once ('config.php');
/**
* Su dung cho lenh: insert/update/delete
*/
function execute($sql) {
// Them du lieu vao database
//B1. Mo ket noi toi database
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
mysqli_set_charset($conn, 'utf8');
//B2. Thuc hien truy van insert
mysqli_query($conn, $sql);
//B3. Dong ket noi database
mysqli_close($conn);
}
/**
* Su dung cho lenh: select
*/
function executeResult($sql, $isSingle = false) {
// Them du lieu vao database
//B1. Mo ket noi toi database
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
mysqli_set_charset($conn, 'utf8');
//B2. Thuc hien truy van insert
$resultset = mysqli_query($conn, $sql);
$data = [];
if($isSingle) {
$data = mysqli_fetch_array($resultset, 1);
} else {
while (($row = mysqli_fetch_array($resultset, 1)) != null) {
$data[] = $row;
}
}
//B3. Dong ket noi database
mysqli_close($conn);
return $data;
}
#utility.php
<?php
function getGET($key) {
$value = '';
if (isset($_GET[$key])) {
$value = $_GET[$key];
}
$value = fixSqlInjection($value);
return $value;
}
function getPOST($key) {
$value = '';
if (isset($_POST[$key])) {
$value = $_POST[$key];
}
$value = fixSqlInjection($value);
return $value;
}
function fixSqlInjection($str) {
$str = str_replace("\\", "\\\\", $str);
$str = str_replace("'", "\'", $str);
return $str;
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)