PHP 商品筛选功能是指在电子商务网站中,用户可以根据不同的条件(如价格区间、品牌、分类等)来筛选商品的功能。这种功能通常涉及到前端和后端的交互,前端负责展示筛选条件和结果,后端负责处理筛选逻辑并返回符合条件的商品数据。
适用于各种电子商务网站、在线市场、二手交易平台等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>商品筛选</title>
</head>
<body>
<form id="filterForm">
<label for="priceRange">价格区间:</label>
<input type="text" id="priceRange" name="priceRange">
<label for="brand">品牌:</label>
<select id="brand" name="brand">
<option value="">全部</option>
<option value="apple">Apple</option>
<option value="samsung">Samsung</option>
</select>
<button type="submit">筛选</button>
</form>
<div id="productList"></div>
<script>
document.getElementById('filterForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('/filter', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
document.getElementById('productList').innerHTML = '';
data.products.forEach(product => {
const productDiv = document.createElement('div');
productDiv.textContent = `${product.name} - ${product.price}`;
document.getElementById('productList').appendChild(productDiv);
});
});
});
</script>
</body>
</html><?php
header('Content-Type: application/json');
$priceRange = $_POST['priceRange'] ?? '';
$brand = $_POST['brand'] ?? '';
// 假设有一个商品数据库表 products
$sql = "SELECT * FROM products WHERE 1=1";
$params = [];
if (!empty($priceRange)) {
list($minPrice, $maxPrice) = explode('-', $priceRange);
$sql .= " AND price BETWEEN ? AND ?";
$params[] = $minPrice;
$params[] = $maxPrice;
}
if (!empty($brand)) {
$sql .= " AND brand = ?";
$params[] = $brand;
}
// 连接数据库并执行查询
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['products' => $products]);
?>通过以上步骤,你可以实现一个基本的 PHP 商品筛选功能。根据具体需求,还可以进一步优化和扩展。
没有搜到相关的文章