By GokiSoft.com|
10:00 07/05/2021|
Học PHP
[Share Code] Xây dựng website bán điện thoại kết nối database (CSDL) - Lập trình PHP/MySQL
#readme.txt
B1. Tao database
create table category (
id int primary key auto_increment,
name varchar(50) not null,
created_at datetime,
updated_at datetime
);
create table product (
id int primary key auto_increment,
title varchar(200),
price float,
thumbnail varchar(500),
content text,
created_at datetime,
updated_at datetime,
category_id int references category (id)
);
#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);
}
#config.php
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'bt2277');
#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;
}
#add-product.php
<?php
require_once('form-product.php');
$categoryList = executeResult('select * from category');
$id = getGet('id');
$thisProduct = executeResult('select * from product where id = '.$id, true);
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Product - 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>
<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script>
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2 class="text-center">Add Product</h2>
</div>
<div class="panel-body">
<form method="post">
<div class="form-group">
<label for="title">Title:</label>
<input required="true" type="text" class="form-control" id="title" name="title" value="<?=($thisProduct != null)?$thisProduct['title']:''?>">
<input type="text" name="id" value="<?=($thisProduct != null)?$thisProduct['id']:''?>" style="display: none;">
</div>
<div class="form-group">
<label for="thumbnail">Thumbnail:</label>
<input required="true" type="text" class="form-control" id="thumbnail" name="thumbnail" value="<?=($thisProduct != null)?$thisProduct['thumbnail']:''?>">
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" class="form-control" id="price" name="price" value="<?=($thisProduct != null)?$thisProduct['price']:''?>">
</div>
<div class="form-group">
<label for="category_id">Category:</label>
<select required="true" class="form-control" id="category_id" name="category_id">
<option value="">-- Select --</option>
<?php
foreach ($categoryList as $item) {
if($thisProduct != null && $item['id'] == $thisProduct['category_id']) {
echo '<option selected value="'.$item['id'].'">'.$item['name'].'</option>';
} else {
echo '<option value="'.$item['id'].'">'.$item['name'].'</option>';
}
}
?>
</select>
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea class="form-control" id="content" name="content"><?=($thisProduct != null)?$thisProduct['content']:''?></textarea>
</div>
<button class="btn btn-success">Save</button>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#content').summernote({
height: 200,
toolbar: [
['style', ['style']],
['font', ['bold', 'italic', 'underline', 'clear']],
['fontname', ['fontname']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['table', ['table']],
['insert', ['link', 'picture', 'video']],
['misc', ['fullscreen', 'codeview', 'undo', 'redo', 'help']]
]
});
});
</script>
</body>
</html>
#form-product.php
<?php
require_once('../db/dbhelper.php');
require_once('../utils/utility.php');
if(!empty($_POST)) {
$action = getPost('action');
switch ($action) {
case 'delete':
deleteProduct();
break;
default:
$id = getPost('id');
if($id > 0) {
updateProduct();
} else {
addProduct();
}
break;
}
}
function deleteProduct() {
$id = getPost('id');
$sql = 'delete from product where id = '.$id;
execute($sql);
}
function addProduct() {
$title = $price = $thumbnail = $content = $category_id = '';
$title = getPost('title');
$price = getPost('price');
$thumbnail = getPost('thumbnail');
$content = getPost('content');
$category_id = getPost('category_id');
$created_at = $updated_at = date('Y-m-d H:i:s');
$sql = "insert into product(title, price, thumbnail, content, category_id, created_at, updated_at) values ('$title', '$price', '$thumbnail', '$content', $category_id, '$created_at', '$updated_at')";
execute($sql);
}
function updateProduct() {
$title = $price = $thumbnail = $content = $category_id = '';
$title = getPost('title');
$price = getPost('price');
$thumbnail = getPost('thumbnail');
$content = getPost('content');
$category_id = getPost('category_id');
$id = getPost('id');
$updated_at = date('Y-m-d H:i:s');
$sql = "update product set title = '$title', price = '$price', thumbnail = '$thumbnail', content = '$content', category_id = $category_id, updated_at = '$updated_at' where id = $id";
execute($sql);
}
#product-list.php
<?php
require_once('../db/dbhelper.php');
$productList = executeResult('select id, title, thumbnail, price, updated_at from product');
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Product - 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>
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2 class="text-center">Product List</h2>
</div>
<div class="panel-body">
<table class="table table-bordered">
<thead>
<tr>
<th>No</th>
<th>Thumbnail</th>
<th>Title</th>
<th>Price</th>
<th>Updated At</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$count = 0;
foreach ($productList as $item) {
echo '<tr>
<td>'.(++$count).'</td>
<td><img src="'.$item['thumbnail'].'" style="width: 160px;"/></td>
<td>'.$item['title'].'</td>
<td>'.$item['price'].'</td>
<td>'.$item['updated_at'].'</td>
<td><a href="add-product.php?id='.$item['id'].'"><button class="btn btn-warning">Edit</button></a></td>
<td><button class="btn btn-danger" onclick="deleteProduct('.$item['id'].')">Delete</button></td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
function deleteProduct(id) {
option = confirm('Are you sure to delete this product?')
if(!option) return
$.post('form-product.php', {
'action': 'delete',
'id': id
}, function(date) {
location.reload()
})
}
</script>
</body>
</html>
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)