php 实现商品筛选
实现商品筛选功能
在PHP中实现商品筛选功能通常涉及数据库查询、条件构建和前端交互。以下是常见的实现方法:
数据库表设计
商品表(products)和筛选属性表(product_attributes)是基础结构:
CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
price DECIMAL(10,2),
category_id INT
);
CREATE TABLE product_attributes (
id INT PRIMARY KEY AUTO_INCREMENT,
product_id INT,
attribute_name VARCHAR(100),
attribute_value VARCHAR(100)
);
构建筛选查询
使用动态SQL构建筛选条件:
$conditions = [];
$params = [];
if(isset($_GET['category'])) {
$conditions[] = "category_id = :category";
$params[':category'] = (int)$_GET['category'];
}
if(isset($_GET['min_price'])) {
$conditions[] = "price >= :min_price";
$params[':min_price'] = (float)$_GET['min_price'];
}
$where = !empty($conditions) ? 'WHERE ' . implode(' AND ', $conditions) : '';
$sql = "SELECT * FROM products $where";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
多属性筛选实现
对于多属性筛选(如颜色、尺寸等):
if(isset($_GET['attributes'])) {
$attributeConditions = [];
foreach($_GET['attributes'] as $attr => $values) {
$placeholders = [];
foreach($values as $i => $value) {
$param = ":attr_{$attr}_{$i}";
$placeholders[] = $param;
$params[$param] = $value;
}
$attributeConditions[] = "(attribute_name = '{$attr}' AND attribute_value IN (".implode(',', $placeholders)."))";
}
if(!empty($attributeConditions)) {
$sql .= " AND id IN (
SELECT product_id FROM product_attributes
WHERE ".implode(' OR ', $attributeConditions)."
GROUP BY product_id
HAVING COUNT(DISTINCT attribute_name) = ".count($_GET['attributes'])."
)";
}
}
前端筛选表单
创建HTML筛选表单:
<form method="GET" action="products.php">
<div>
<label>价格范围:</label>
<input type="number" name="min_price" placeholder="最低价">
<input type="number" name="max_price" placeholder="最高价">
</div>
<div>
<label>颜色:</label>
<input type="checkbox" name="attributes[color][]" value="red"> 红色
<input type="checkbox" name="attributes[color][]" value="blue"> 蓝色
</div>
<div>
<label>尺寸:</label>
<input type="checkbox" name="attributes[size][]" value="S"> S
<input type="checkbox" name="attributes[size][]" value="M"> M
</div>
<button type="submit">筛选</button>
</form>
性能优化建议
使用索引加速查询:

ALTER TABLE products ADD INDEX idx_category_price (category_id, price);
ALTER TABLE product_attributes ADD INDEX idx_product_attr (product_id, attribute_name, attribute_value);
对于大型电商系统,可以考虑使用Elasticsearch等专业搜索引擎实现更复杂的商品筛选功能。缓存常用筛选结果也能显著提升性能。






