By GokiSoft.com| 21:14 31/01/2024|
Học PHP

Xây dựng website bán hoa quả bằng PHP/MySQL - Lập trình PHP/MySQL

Thiết kế CSDL gồm các bảng sau

- Bảng danh mục sản phẩm: id tự tăng, tên danh  mục, ngày tạo, ngày sửa

- Bảng sản phẩm: id tự tăng, tiêu đề, giá bán, link hình ảnh, nội dung, ngày tạo, ngày sửa, id danh mục

Yêu cầu thiết kế:

- Trang admin gồm các chức năng sau

1) Thêm/sửa/xoá + hiển thị danh sách danh mục sản phẩm

2) Thêm/sửa/xoá + hiển thị danh mục sản phẩm

- Trang Frontend gồm các chức năng sau

1) Trang home => Hiển thị danh sach danh mục sản phẩm => Khi người dùng click vào từng danh mục => gọi tới trang danhmuc.php

2) Trang danhmuc.php => hiển thị danh sách sản phẩm trong danh mục đó

3) Khi click vào từng sản phẩm => Hiển thị ra trang chi tiết sản phẩm

P/S: Sử dụng bootstrap/jquery thiết kế website (nhanh & đẹp)

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

5

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


GokiSoft.com [Teacher]
GokiSoft.com

2021-06-16 08:57:26


#utility.php


<?php
function fixSqlInjection($str) {
	// abc\okok -> abc\\okok
	//abc\okok (user) -> abc\okok (server) -> sql (abc\okok) -> xuat hien ky tu \ -> ky tu dac biet -> error query
	//abc\okok (user) -> abc\okok (server) -> convert -> abc\\okok -> sql (abc\\okok) -> chinh xac
	$str = str_replace('\\', '\\\\', $str);
	//abc'okok -> abc\'okok
	//abc'okok (user) -> abc'okok (server) -> sql (abc'okok) -> xuat hien ky tu \ -> ky tu dac biet -> error query
	//abc'okok (user) -> abc'okok (server) -> convert -> abc\'okok -> sql (abc\'okok) -> chinh xac
	$str = str_replace('\'', '\\\'', $str);

	return $str;
}

function authenToken() {
	if (isset($_SESSION['user'])) {
		return $_SESSION['user'];
	}

	$token = getCOOKIE('token');
	if (empty($token)) {
		return null;
	}

	$sql    = "select users.* from users, login_tokens where users.id = login_tokens.id_user and login_tokens.token = '$token'";
	$result = executeResult($sql);

	if ($result != null && count($result) > 0) {
		$_SESSION['user'] = $result[0];

		return $result[0];
	}

	return null;
}

function getPOST($key) {
	$value = '';
	if (isset($_POST[$key])) {
		$value = $_POST[$key];
	}
	return fixSqlInjection($value);
}

function getCOOKIE($key) {
	$value = '';
	if (isset($_COOKIE[$key])) {
		$value = $_COOKIE[$key];
	}
	return fixSqlInjection($value);
}

function getGET($key) {
	$value = '';
	if (isset($_GET[$key])) {
		$value = $_GET[$key];
	}
	return fixSqlInjection($value);
}

function md5Security($pwd) {
	return md5(md5($pwd).MD5_PRIVATE_KEY);
}


#dbhelper.php


<?php
require_once ('config.php');

/**
 * Su dung voi cau lenh query: insert, update, delete -> ko tra ve ket qua.
 */
function execute($sql) {
	//Mo ket noi toi database
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	//Xu ly cau query
	mysqli_query($conn, $sql);

	//Dong ket noi database
	mysqli_close($conn);
}

/**
 * Su dung voi cau lenh query: select.
 */
function executeResult($sql, $isSingleRecord = false) {
	//Mo ket noi toi database
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	// echo $sql;
	//Xu ly cau query
	$resultset = mysqli_query($conn, $sql);
	// var_dump($resultset);
	// die();
	if ($isSingleRecord) {
		$data = mysqli_fetch_array($resultset, 1);
	} else {
		$data = [];
		while (($row = mysqli_fetch_array($resultset, 1)) != null) {
			$data[] = $row;
		}
	}

	/**
	 * TH: param2 = 1
	 * $row = [
	 * 		'id' => 1,
	 * 		'title' => '1 - Android Tivi Sony 4K 55 inch KD-55X8000H',
	 * 		'thumbnail' => '12321',
	 * 		...
	 * ];
	 *
	 * TH: param2 = 2
	 * $row = [1, '1 - Android Tivi Sony 4K 55 inch KD-55X8000H', '12321', ...];
	 */

	//Dong ket noi database
	mysqli_close($conn);

	return $data;
}


#config.php


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

define('MD5_PRIVATE_KEY', '2342kuhskdfsd23(&kusdhfjsgJYGJGsfdf384');


#product.php


<?php
session_start();
header('Access-Control-Allow-Origin: *');

require_once ('../db/dbhelper.php');
require_once ('../utils/utility.php');

$action = getPOST('action');

switch ($action) {
	case "add":
		addProduct();
		break;
	case "update":
		updateProduct();
		break;
	case "remove":
		removeProduct();
		break;
	case "list":
		showListProduct();
		break;
}

function addProduct() {
	$title     = getPOST('title');
	$price     = getPOST('price');
	$thumbnail = getPOST('thumbnail');
	$content   = getPOST('content');

	$sql = "insert into product (title, price, thumbnail, content) values ('$title', '$price', '$thumbnail', '$content')";
	execute($sql);

	$res = [
		"status" => 1,
		"msg"    => "Thanh cong."
	];
	echo json_encode($res);
}

function updateProduct() {
	$id        = getPOST('id');
	$title     = getPOST('title');
	$price     = getPOST('price');
	$thumbnail = getPOST('thumbnail');
	$content   = getPOST('content');

	$sql = "update product set title = '$title', price = '$price', thumbnail = '$thumbnail', content = '$content' where id = $id";
	execute($sql);

	$res = [
		"status" => 1,
		"msg"    => "Thanh cong."
	];
	echo json_encode($res);
}

function removeProduct() {
	$id = getPOST('id');

	$sql = "delete from product where id = $id";
	execute($sql);

	$res = [
		"status" => 1,
		"msg"    => "Thanh cong."
	];
	echo json_encode($res);
}

function showListProduct() {
	$s = getPOST('s');

	if (!empty($s)) {
		$sql = "select * from Product where title = '%$s%' order by title asc";
	} else {
		$sql = "select * from Product order by title asc";
	}
	$data = executeResult($sql);
	echo json_encode($data);
}

//CRUD - create update delete


#category.php


<?php
session_start();
header('Access-Control-Allow-Origin: *');

require_once ('../db/dbhelper.php');
require_once ('../utils/utility.php');

$action = getPOST('action');

switch ($action) {
	case "add":
		addCategory();
		break;
	case "update":
		updateCategory();
		break;
	case "remove":
		removeCategory();
		break;
	case "list":
		showListCategory();
		break;
}

function addCategory() {
	$name = getPOST('name');

	$sql = "insert into category (name) values ('$name')";
	execute($sql);

	$res = [
		"status" => 1,
		"msg"    => "Thanh cong."
	];
	echo json_encode($res);
}

function updateCategory() {
	$name = getPOST('name');
	$id   = getPOST('id');

	$sql = "update category set name = '$name' where id = $id";
	execute($sql);

	$res = [
		"status" => 1,
		"msg"    => "Thanh cong."
	];
	echo json_encode($res);
}

function removeCategory() {
	$id = getPOST('id');

	$sql = "delete from category where id = $id";
	execute($sql);

	$res = [
		"status" => 1,
		"msg"    => "Thanh cong."
	];
	echo json_encode($res);
}

function showListCategory() {
	$s = getPOST('s');

	if (!empty($s)) {
		$sql = "select id, name, updated_at from category where name = '%$s%' order by name asc";
	} else {
		$sql = "select id, name, updated_at from category order by name asc";
	}
	$data = executeResult($sql);
	echo json_encode($data);
}


#readme.txt


B1) Phân tích database
- create database BT1947
- create tables

create table category (
	id int primary key auto_increment,
	name varchar(100) not null,
	created_at datetime,
	updated_at datetime,
	href_param varchar(100)
);

create table product (
	id int primary key auto_increment,
	title varchar(250) not null,
	price float,
	thumbnail varchar(500),
	content longtext,
	created_at datetime,
	updated_at datetime
);

B2) Fake data -> DONE
B3) Phan tich API
B4) Phat trien chuc nang API (server)
- Xay dung bo khung chuong trinh
- db
	config.php
	dbhelper.php
- utils
	utility.php
- api
	category.php
	product.php


#config.js


var BASE_URL = 'http://localhost/aptech/T2008A/lesson08/server/';

// Category API
var API_CATEGORY = 'api/category.php';

// Product API


#category.html


<!DOCTYPE html>
<html>
<head>
	<title>Category Page</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>

	<script type="text/javascript" src = "js/config.js"></script>
</head>
<body>
	<div class="container">
		<table class="table table-bordered">
			<thead>
				<tr>
					<th>No</th>
					<th>Name</th>
					<th>Updated At</th>
					<th style="width: 50px;"></th>
					<th style="width: 50px;"></th>
				</tr>
			</thead>
			<tbody id="result"></tbody>
		</table>
	</div>

	<script type="text/javascript">
		$(function() {
			$.post(BASE_URL + API_CATEGORY, {
					'action': 'list',
					's': ''
			}, function(data) {
				// console.log(data)
				result = JSON.parse(data)
				for(i=0;i<result.length;i++) {
					$('#result').append(`<tr>
							<td>${i+1}</td>
							<td>${result[i].name}</td>
							<td>${result[i].updated_at}</td>
							<td><button class="btn btn-warning">Edit</button></td>
							<td><button class="btn btn-danger" onclick="removeItem(${result[i].id})">Remove</button></td>
						</tr>`)
				}
			})
		})

		function removeItem(id) {
			var option = confirm('Ban co chac chan muon xoa danh muc nay khong?')
			if(!option) return

			$.post(BASE_URL + API_CATEGORY, {
					'action': 'remove',
					'id': id
			}, function(data) {
				// console.log(data)
				location.reload()
			})
		}
	</script>
</body>
</html>



Trung Hiếu [community]
Trung Hiếu

2020-09-30 02:03:11

Đây là bài tập của em. Em là Trung Hiếu ở lớp C2002L

https://github.com/HieuMilieu/PHP---Quan-Ly-Ban-Hang.git