By GokiSoft.com| 20:03 21/05/2021|
Học PHP

[Share Code] Sử dụng 100% Cookie Javascript - Trang quản lý sản phẩm php - Lập trình PHP


#config.php


<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'quanlysanpham');


#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;
}


#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>
	<?php
		$cart = '[]';
		if(isset($_COOKIE['cart'])) {
			$cart = $_COOKIE['cart'];
		}
	?>

	<script type="text/javascript">
		//Gio hang => cookie => key: cart
		var cartList = JSON.parse('<?=$cart?>')

		$(function() {
			var total = 0
			for (var i = 0; i < cartList.length; i++) {
				total += cartList[i].num
			}
			$('#cart_num').html(total)
		})
	</script>
</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="index.php">Home</a>
		    </li>
		    <li class="nav-item">
		      <a class="nav-link" href="index.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>
			<a href="cart.php">
				<button type="button" class="btn btn-primary">
					Cart <span class="badge badge-light" id="cart_num">0</span>
				</button>
			</a>
	  </div>
	</nav>
	<!-- header END -->

	<div class="container main">


#cart.php


<?php
$title = 'Product Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');

$sql = 'select * from product';
$productList = executeResult($sql);
?>
<!-- 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 id="result">
			</tbody>
		</table>
		<p style="color: red; font-size: 32px;" id="total_money"></p>
		<button class="btn btn-success" style="width: 100%; padding: 10px; font-size: 32px;">Checkout</button>
	</div>
</div>
<!-- body END -->
<?php
include_once('layouts/footer.php');
?>

<script type="text/javascript">
	$(function() {
		var total = 0
		for (var i = 0; i < cartList.length; i++) {
			total += cartList[i].price*cartList[i].num
			$('#result').append(`
				<tr>
					<td>${i+1}</td>
					<td><img src="${cartList[i].thumbnail}" style="width: 160px"></td>
					<td>${cartList[i].title}</td>
					<td>${cartList[i].price} vnd</td>
					<td>${cartList[i].num}</td>
					<td>${cartList[i].price*cartList[i].num} vnd</td>
					<td><button class="btn btn-danger" onclick="deleteItem(${cartList[i].id})">Delete</button></td>
				</tr>`)
		}
		$('#total_money').html(total + ' vnd')
	})

	function deleteItem(id) {
		for (var i = 0; i < cartList.length; i++) {
			if(cartList[i].id == id) {
				cartList.splice(i, 1)
				break
			}
		}

		var now = new Date();
		var time = now.getTime();
		var expireTime = time + 30*24*60*60*1000;
		now.setTime(expireTime);

		document.cookie = "cart="+JSON.stringify(cartList)+";path=/;expires="+now.toUTCString()

		location.reload()
	}
</script>


#detail.php


<?php
$title = 'Product Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');

$id = 0;
if(isset($_GET['id'])) {
	$id = $_GET['id'];
}
$sql = "select * from product where id = $id";
$product = executeResult($sql, 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: 32px;"><?=$product['title']?></p>
		<p style="font-size: 32px;">Tra Gop: <?=$product['percent']?></p>
		<p style="font-size: 32px; color: red"><?=number_format($product['price'], 0, '', '.')?></p>
		<button class="btn btn-success" style="width: 100%; padding: 10px; font-size: 26px;" onclick="addToCart()">Add to cart</button>
	</div>
</div>
<!-- body END -->
<script type="text/javascript">
	function addToCart() {
		var id = '<?=$product['id']?>'
		var thumbnail = '<?=$product['thumbnail']?>'
		var title = '<?=$product['title']?>'
		var price = '<?=$product['price']?>'

		var isFind = false
		for (var i = 0; i < cartList.length; i++) {
			if(cartList[i].id == id) {
				cartList[i].num++
				isFind = true
				break
			}
		}

		if(!isFind) {
			cartList.push({
				"id": id,
				"thumbnail": thumbnail,
				"title": title,
				"price": price,
				"num": 1
			})
		}

		console.log(cartList)

		var now = new Date();
		var time = now.getTime();
		var expireTime = time + 30*24*60*60*1000;
		now.setTime(expireTime);

		document.cookie = "cart="+JSON.stringify(cartList)+";path=/;expires="+now.toUTCString()

		//Dem so phan tru trong gio hang
		var total = 0
		for (var i = 0; i < cartList.length; i++) {
			total += cartList[i].num
		}
		$('#cart_num').html(total)
	}
</script>
<?php
include_once('layouts/footer.php');
?>


#index.php


<?php
$title = 'Product Page';
include_once('layouts/header.php');
require_once('db/dbhelper.php');

$sql = 'select * from product';
$productList = executeResult($sql);
?>
<!-- body START -->
<div class="row">
<?php
foreach ($productList as $item) {
	echo '<div class="col-md-3 col-6" style="text-align: center; margin-top: 10px; border: solid 1px #e3e2e2;">
			<button class="btn btn-success" style="margin-top: 5px;">Tra Gop '.$item['percent'].'</button>
			<a href="detail.php?id='.$item['id'].'"><img src="'.$item['thumbnail'].'" style="width: 100%"></a>
			<a href="detail.php?id='.$item['id'].'"><p>'.$item['title'].'</p></a>
			<p style="color: red">'.number_format($item['price'], 0, '', '.').' vnd</p>
		</div>';
}
?>
</div>
<!-- body END -->
<?php
include_once('layouts/footer.php');
?>


#readme.txt


B1. Tao database
- create database quanlysanpham

create table product (
	id int primary key auto_increment,
	title varchar(300) not null,
	thumbnail varchar(500),
	price float,
	percent float
)
B2. Fake data -> DONE
	- UPDATE `product` SET `title` = concat(`id`, '-', `title`)
B3. Xay dung bo khung chuong trinh
B4. Xay dung chuc nang cua du an
- Thiết kế trang nhập, sửa, xoá, hiển thị danh sách sản phẩm -> admin -> theo doi trong video truoc.
- Frontend
	- index.php -> Hien thi danh sach san pham
	- detail.php -> Hien thi chi tiet san pham
	- cart.php -> Hien thi thong tin gio hang -> Cookie
		cookie -> luu du lieu -> key => value
			cart => [
				{
					"id": ???,
					"num": ???,
					"title": ???,
					"thumbnail": ???,
					"price": ???
				}, {
					"id": ???,
					"num": ???,
					"title": ???,
					"thumbnail": ???,
					"price": ???
				}, {
					"id": ???,
					"num": ???,
					"title": ???,
					"thumbnail": ???,
					"price": ???
				}
			]


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)