Từng bước học lập trình php căn bản qua dự án website giới thiệu sản phẩm – Tạo trang danh sách sản phẩm

Tại thư mục gốc (Root), các bạn tạo mới file product-list.php để viết mã lệnh xử lý trang danh sách sản phẩm.

Nội dung file product-list.php như sau:

<?php
//Require các file cần thiết
require ‘configs/config.php’;
require ‘libraries/connect.php’;
require ‘models/product.php’;

//Lấy category_id từ URL (Nếu có)
$category_id = isset($_GET[‘category_id’]) ? ((int)$_GET[‘category_id’]) : null;

//Lấy danh sách sản phẩm
$product_active_list = get_product_active_list($category_id);

//Require file giao diện (View)
require ‘views/front/product/list.tpl.php’;
?>

Mở file models/product.php và viết thêm vào khối lệnh mới dưới đây:

function get_product_active_list($category_id){
//SQL
$sql = “SELECT * FROM tbl_product WHERE status = 1”;

//Nếu lấy sản phẩm theo danh mục
if($category_id != null){
$sql .= ” AND category_id = $category_id”;
}

//Sắp xếp
$sql .= ” ORDER BY product_id DESC”;

//Query và return
return mysql_query($sql);
}

Trong thư mục views/front, tạo mới thư mục tên là product để chứa các file trình bày giao diện các trang sản phẩm.

Trong thư mục views/front/product, tạo mới file list.tpl.php để trình bày giao diện trang danh sách sản phẩm.

Nội dung file views/front/product/list.tpl.php như sau:

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Website giới thiệu sản phẩm – Danh sách sản phẩm</title>
</head>
<body>

<?php while($product_active = mysql_fetch_assoc($product_active_list)): ?>
<div style=”padding:10px;”>
<p>
<img src=”<?php echo SITE_URL . ‘userfiles/’ . $product_active[‘image’]; ?>” />
</p>
<h4>
<a href=”<?php echo SITE_URL . ‘product-detail.php?product_id=’ . $product_active[‘product_id’]; ?>”><?php echo $product_active[‘name’]; ?></a>
</h4>
<p><?php echo number_format($product_active[‘price’], 0, ”, ‘.’); ?> VNĐ</p>
</div>
<?php endwhile; ?>

</body>
</html>

Các bạn truy cập trang danh sách sản phẩm theo địa chỉ http://localhost/product-list.php để kiểm tra.

Tác giả: Lê Trung Hiếu

Viết một bình luận