Gần đây trên 2mit tôi đọc một bài viết của chú @white.smut (link:http://2mit.org/forum/threads/php-xay-dung-gio-hang-cho-website-ban-hang.31356/) viết về cách tạo giỏ hàng trong php nhưng cách này có một vấn đề là nó không tự xóa được giỏ hàng khi đóng trình duyệt, điều này là lỗ hổng để tin tặc có thể tấn công làm quá tải server.
Bài sau đây tôi sẽ hướng dẫn bạn sử dụng biến $_SESSION thay vì table để giải quyết vấn đề trên
trước hết ta cần chuẩn bị 2 file
connect.php
PHP:
<?php
$host = 'localhost';//host của mysql
$user = 'root';// user của mysql
$pass = '';// pass của mysql
$db_name = 'test_cart'; // tên CSDL
mysql_connect($host,$user,$pass) or die('Cannot connect to db');
mysql_select_db($db_name);
mysql_query('set names utf8');
?>
và function.php
PHP:
<?php function guid(){
if (function_exists('com_create_guid')){
return com_create_guid();
}else{
mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45);// "-"
$uuid = chr(123)// "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.chr(125);// "}"
return $uuid;
}
} ?>
file function.php này có chức năng là chứa các hàm do coder tự định nghĩa ra, hiện thời mình chỉ dùng hàm guid để tạo cart guid.
tiếp theo là file index.php
PHP:
<?php ob_start();
session_start();
include 'connect.php';
include 'functions.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test_cart</title>
<link rel="stylesheet" href="icon/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="wrapper">
<?php $act = (isset($_GET['act'])) ? $_GET['act'] : 'sanpham' ?>
<?php switch ($act) {
case 'sanpham':
include 'sanpham.php';
break;
case 'giohang':
include 'giohang.php';
break;
case 'themgiohang':
include 'them.php';
break;
case 'hoadon':
include 'hoadon.php';
break;
case 'xemhoadon':
include 'admin/hoadon.php';
break;
default:
exit;
break;
} ?>
</div><!-- end #wrapper -->
</body>
</html>
<?php
session_commit();
ob_end_flush();
?>
và file sanpham.php
PHP:
<?php $res = mysql_query("SELECT id_product,name, thumb, remain, price FROM products") or die('cannot select table');
if(mysql_num_rows($res)!=0):
while($fetch = mysql_fetch_assoc($res)):
?>
<div class="products">
<h2><?php echo $fetch['name']; ?></h2>
<img src="<?php echo $fetch['thumb'] ?>" alt="thumbnail">
<div class="remain">Số lượng: <?php echo $fetch['remain'] ?></div>
<div class="price">Giá: <?php echo $fetch['price'] ?></div>
<div class="btn">
<a href="?act=themgiohang&id_product=<?php echo $fetch['id_product'] ?>" class="add fa fa-shopping-cart"></a>
<a href="#" class="detail fa fa-book"></a>
</div>
</div><!-- end .products -->
<?php
endwhile;//end while($fetch = mysql_fetch_assoc($res))
endif;//end if(mysql_num_rows($res)!=0)
?>
file them.php - file này có chức năng thêm sản phẩm vào giỏ hàng
PHP:
<?php $res = mysql_query('SELECT id_product, name, thumb, remain, price FROM products WHERE id_product = '.$_GET['id_product']) or die('cannot select table') ?>
<?php
$stop = false;
while ($fetch = mysql_fetch_assoc($res)) {
if(isset($_SESSION['cart'])){
foreach ($_SESSION['cart'] as $key => $cart) {
if($cart['id_product'] == $fetch['id_product']){
$_SESSION['cart'][$key]['number'] += 1;
$stop = true;
}//end if($cart['id_product']) = $fetch['id_product']
}//end foreach (($_SESSION['cart'] as $key => $cart)
}//end if(isset($_SESSION['cart']))
if (!$stop) {
$fetch['number']=1;
$_SESSION['cart'][]=$fetch;
}
}//while ($fetch = mysql_fetch_assoc($res))
header('location:?act=giohang');
exit;
?>
Ở file này bạn sẽ thấy có sự khác biệt so với cách thêm của bạn @white.smut thay vì thêm vào bảng, nó sẽ thêm giá trị vào biến $_SESSION['cart'], nó sẽ kiểm tra nếu sản phẩm đã được thêm rồi, thì nó chỉ cộng vào số lượng, còn nếu không thì nó sẽ thêm một giá trị mới vào biến session này
tiếp theo là file giohang.php file này mình gộp cả sửa, xóa vào luôn
PHP:
<?php /********THEM*******/ ?>
<?php if (isset($_POST['update'])) {
foreach ($_SESSION['cart'] as $key => $value) {
$_SESSION['cart'][$key]['number'] = $_POST[$key];
}
header('location:'.$_SERVER['REQUEST_URI']);
}//end if (isset($_POST['update'])) ?>
<?php /******XOA*******/ ?>
<?php if (isset($_POST['del'])) {
foreach ($_POST['chk'] as $value) {
unset($_SESSION['cart'][$value]);
}
header('location:'.$_SERVER['REQUEST_URI']);
} ?>
<?php $i=1; ?>
<form method="post">
<table>
<thead>
<tr>
<td>STT</td>
<td>Tên</td>
<td>Số lượng</td>
<td>Đơn Giá</td>
<td>Tổng</td>
<td>Chọn</td>
</tr>
</thead>
<tbody>
<?php foreach ($_SESSION['cart'] as $key => $cart): ?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $cart['name'] ?></td>
<td>
<input type="text" name="<?php echo $key ?>" value="<?php echo $cart['number'] ?>">
</td>
<td><?php echo $cart['price'] ?></td>
<td><?php echo $cart['number']*$cart['price'] ?></td>
<td><input type="checkbox" name="chk[]" value="<?php echo $key ?>"></td>
</tr>
<?php $i++ ?>
<?php endforeach ?>
</tbody>
</table>
<div class="table-btn">
<a href="?act=sanpham" class="back"><i class="fa fa-chevron-left"></i> Quay về</a>
<input type="submit" value="delete" name="del">
<input type="submit" value="update" name="update">
<a href="?act=hoadon" class="back"><i class="fa fa-chevron-right"></i> Lưu vào đơn hàng</a>
</div>
</form><!-- end form -->
thay vì phải sử dụng những câu lệnh của mysql thì file này sẽ dùng lệnh gán để thay đổi giá trị của khóa được chỉ định trong $_SESSION['Cart'], và dùng lệnh uset để xóa giá trị được chỉ định.
sau đó sẽ dùng vòng lặp foreach để hiện thị dữ liệu ra bảng
và file hoadon.php
PHP:
<?php
$success = true;
if (!isset($_SESSION['uuid'])) {
$_SESSION['uuid'] = guid();
}//end if (!isset($_SESSION['uuid']))
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key => $value) {
$res = mysql_query('INSERT INTO orders(uuid,id_product,numbers,status) VALUES ("'.$_SESSION['uuid'].'",'.$value['id_product'].','.$value['number'].',0)');
if(!$res){
$success = false;
}//end if(!$res)
}//end foreach ($_SESSION['cart'] as $key => $value)
if($success){
$_SESSION['cart']=NULL;
header('location:?act=hoadon');
}
}//end if(isset($_SESSION['cart'])) ?>
<?php $res = mysql_query('SELECT DISTINCT uuid FROM orders'); ?>
<?php if (mysql_num_rows($res)!=0 && !isset($_GET['uuid'])): ?>
<?php $i=1; ?>
<table>
<thead>
<tr>
<td>STT</td>
<td>GUID</td>
<td>Chi tiết</td>
</tr>
</thead>
<tbody>
<?php
while ($fetch = mysql_fetch_assoc($res)):?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $fetch['uuid'] ?></td>
<td><a href="?act=hoadon&uuid=<?php echo urlencode($fetch['uuid']) ?>">Chi tiết</a></td>
</tr>
<?php
$i++;
endwhile;//end while ($fetch = mysql_fetch_assoc($res))
?>
</tbody>
</table>
<?php endif;//end if (mysql_num_rows($res)!=0) ?>
<?php if (isset($_GET['uuid'])): ?>
<table>
<thead>
<tr>
<td>STT</td>
<td>Tên</td>
<td>Số lượng</td>
<td>Tình trạng</td>
</tr>
</thead>
<tbody>
<?php
$res = mysql_query('SELECT name, numbers, status FROM orders od JOIN products p ON p.id_product = od.id_product
WHERE uuid = "'.$_GET['uuid'].'"');
$i=1;
while($fetch = mysql_fetch_assoc($res)):
?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $fetch['name'] ?></td>
<td><?php echo $fetch['numbers'] ?></td>
<td><?php echo $fetch['status'] ?></td>
</tr>
<?php
$i++;
endwhile
?>
</tbody>
</table>
<div class="table-btn"><a href="?act=hoadon">Trở về</a></div>
<?php endif ?>
Đến file này chúng ta sẽ quay lại với mysql, lúc này chúng ta sẽ dùng các lệnh quen thuộc để chèn dữ liệu từ biến $_SESSION['cart'] vào giỏ hàng. ở đây tôi thay session_id bằng $_SESSION['uuid']
vì vấn đề về thời gian nên tôi chỉ dừng lại ở chức năng hiển thị
và cuối cùng là file thống kê hóa đơn dành cho admin
PHP:
<table>
<thead>
<tr>
<td>STT</td>
<td>Tên</td>
<td>Số lượng</td>
<td>Tình trạng</td>
</tr>
</thead>
<tbody>
<?php
$res = mysql_query('SELECT name, numbers, status FROM orders od JOIN products p ON p.id_product = od.id_product');
$i=1;
while($fetch = mysql_fetch_assoc($res)):
?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $fetch['name'] ?></td>
<td><?php echo $fetch['numbers'] ?></td>
<td><?php echo $fetch['status'] ?></td>
</tr>
<?php
$i++;
endwhile
?>
</tbody>
</table>
file đính kèm ở đây:
http://www.mediafire.com/download/ai87w2simquav18/cart.rar