By GokiSoft.com|
11:31 19/05/2021|
Học PHP
[Share Code]Trang quản lý sản phẩm php - Lập trình PHP - C2010G
#readme.txt
B1. Tạo CSDL (database)
- create database quanlysanpham
create table products (
id int primary key auto_increment,
title varchar(250) not null,
thumbnail varchar(500),
price float,
percent float
)
B2. Fake data -> DONE
B3. Xây dựng khung dự án
- db:
- config.php
- dbhelper.php
- utils
- utility.php
#cart.php
<?php
session_start();
require_once('db/dbhelper.php');
require_once('utils/utility.php');
include_once('layouts/header.php');
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
?>
<!-- body -->
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<th>
<th>No</th>
<th>Thumbnail</th>
<th>Title</th>
<th>Price</th>
<th>Num</th>
<th>Total</th>
<th></th>
</th>
</thead>
<tbody>
<?php
$count = 0;
$total = 0;
foreach ($cart as $item) {
$total += $item['num']*$item['price'];
echo '
<tr>
<td>'.(++$count).'</td>
<td><img src="'.$item['thumbnail'].'" style="height: 100px"/></td>
<td>'.$item['title'].'</td>
<td>'.$item['num'].'</td>
<td>'.number_format($item['price'], 0, ',', '.').'</td>
<td>'.number_format($item['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>
<button class="btn btn-success" style="width: 100%; font-size: 32px;">Checkout</button>
</div>
</div></div>
<script type="text/javascript">
function deleteCart(id) {
$.post('api/api-product.php', {
'action': 'delete',
'id': id
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#detail.php
<?php
session_start();
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);
?>
<!-- body -->
<div class="container">
<div class="row">
<div class="col-md-5">
<img src="<?=$product['thumbnail']?>" style="width: 100%">
</div>
<div class="col-md-7">
<h3><?=$product['title']?></h3>
<p style="color: red; font-size: 30px;"><?=number_format($product['price'], 0, '', '.')?> vnđ</p>
<select class="form-control" style="width: 120px;" id="num">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<button class="btn btn-success" onclick="addToCart(<?=$id?>)" style="font-size: 32px; width: 100%; padding: 10px; margin-top: 10px;">Add to cart</button>
</div>
</div>
</div>
<script type="text/javascript">
function addToCart(id) {
$.post('api/api-product.php', {
'id': id,
'action': 'add',
'num': $('#num').val()
}, function(data) {
location.reload()
})
}
</script>
<?php
include_once('layouts/footer.php');
?>
#index.php
<?php
session_start();
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" style="padding: 5px; border: solid 1px #e4e3e3; text-align: center;">
<button class="btn btn-success">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, '', '.').' vnđ</p>
</div>';
}
?>
</div>
</div>
<?php
include_once('layouts/footer.php');
?>
#api-product.php
<?php
session_start();
require_once('../db/dbhelper.php');
require_once('../utils/utility.php');
if(!empty($_POST)) {
$id = getPost('id');
$action = getPost('action');
switch ($action) {
case 'add':
addToCart($id);
break;
case 'delete':
deleteItem($id);
break;
}
}
/**
$_SESSION['cart'] = [
[
object => product,
'key' => value,
'num': ???
],
[
object => product,
'num': ???
],
[
object => product,
'num': ???
]
]
*/
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['cart'] = $cart;
}
function addToCart($id) {
$num = getPost('num');
$cart = [];
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
//Kiem tra $id da ton tai trong $cart
$isFind = false;
for ($i=0; $i < count($cart); $i++) {
if($cart[$i]['id'] == $id) {
$cart[$i]['num'] += $num;
$isFind = true;
break;
}
}
if(!$isFind) {
$product = executeResult("select * from products where id = $id", true);
$product['num'] = $num;
$cart[] = $product;
}
//update
$_SESSION['cart'] = $cart;
}
#config.php
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'quanlysanpham');
#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;
}
#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="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="#">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($_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>
#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);
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)