要使您的过滤器更加动态,请将它们注册到数据库中,如下所示:
您可以创建一个model_filters
表(例如在 mysql 中):
drop table if exists model_filters;
create table model_filters (
id int not null auto_increment primary key,
name varchar(80) not null,
model varchar(80) not null,
condition varchar(40) not null,
created datetime,
modified datetime,
active boolean not null default 1,
index model_filters (name)
);
因此,为特定模型创建一些过滤器:
INSERT INTO model_filters VALUES
('Age Above' , 'user' ,'age <= %filter'),
('Age Below' , 'user' ,'age >= %filter'),
('City' , 'user' ,'city ="%filter"'),
('Gender' , 'user' ,'gender = "%filter"');
然后,根据您的模型获取过滤器:
SELECT id, name FROM model_filters WHERE model = 'user' AND active = 1
迭代这些值并生成一个过滤器<select>
:
<select name="filters" id="filters">
<option value="1">Age Above</option>
<option value="2">Age Below</option>
<option value="3">City</option>
<option value="4">Gender</option>
</select>
<input type="text" name="value" id="value">
并且,您获得此信息,搜索选定的过滤器,然后执行您的查询
<?php
// I'm using PDO
$statment = $pdo->prepare("SELECT * FROM model_filters WHERE id = :id");
$statment->bindValue(':id', $_POST['filters']);
$status = $statment->execute();
$result = null;
if ($status == true) {
$result = $statment->fetchAll(PDO::FETCH_ASSOC);
}
if ($result == null) {
// ERROR!
}
现在,组织值
/*
$result['condition'] is equal (for example): "age <= %filter"
After replace is = "age <= :filter"
Obs.: replace for whatever you want, for example: ":filtername, :value, :whatever"
*/
$condition = str_replace('%filter', ':filter', $result['condition']);
$statment = $pdo->prepare("SELECT * FROM Users1 WHERE $condition");
$statment->bindValue(':filter', $_POST['value']);
$status = $statment->execute();
$result = null;
if ($status == true) {
$result = $statment->fetchAll(PDO::FETCH_ASSOC);
}
获取$result
、发送以供您查看,并迭代过滤的用户。
完毕!