我正在尝试创建一个搜索查询:
我给出了6个搜索选项。
- 卧室
- 类型
- 邮编
- 位置
- 最低价格
- 最高价格
我在表格中有这些字段。我搜索了很多,但找不到我正在搜索的答案。我也尝试过使用LIKE
和%
进行查询。但这也没有成功。
如果用户只选择"类型",则应显示该类型的所有数据。其他领域也是如此。
同样,如果用户选择2或3个选项并进行搜索,则应显示与所选选项匹配的结果。
如何创建这样的搜索?我该怎么做?:
if(){
}else if(){
}
您可以动态构建sql查询。如果搜索值不为空(或其他不算作搜索值的值),则不要添加搜索。不要忘记将mysql_real_eescape_string添加到params中,否则坏人会利用你的软件。
php中的示例:
<?php
$params = array('type' => 'aaa', 'max_price'=>100); // parameters that a user gave. Example from $_POST or $_GET
$querySearch = array();
if(isset($params['type'])) {
$querySearch[] = "type LIKE '%".mysql_real_escape_string($params['type'])."%'";
}
if(isset($params['max_price'])) {
$querySearch[] = "price <= ".mysql_real_escape_string($params['max_price']);
}
if(isset($params['min_price'])) {
$querySearch[] = "price >= ".mysql_real_escape_string($params['min_price']);
}
// and etc.
$q = 'select * FROM hotel WHERE ' . implode(' AND ' , $querySearch);
echo $q;
?>
然后可以使用查询$q来进行数据库选择。
动态构建查询
$useAnd = false;
$ query = " select * from table";
if (isset($bedrooms) == true or isset($type) == true or isset($postcode)==true or ...)
{
$query = $query. " where ";
if (isset($bedroomsIsset) = true)
{
$query = $query . "bedrooms >=". $bedrooms; $useAnd=true;
}
if (isset($type) = true)
{
if ($useAnd=true)
{$query = $query . " and " ;}
$query = $query . "type =". $type; $useAnd=true;
}
if (isset($postcode)==true)
{
if (isset($poscode) = true)
{
if ($useAnd=true)
{$query = $query . " and " ;}
$query = $query . "postcode =". $postcode; $useAnd=true;
}
if (...)
}
if(!empty($some_option)) $search_options["option_name"] = $some_option;
$query = "some query";
$where = "";
if(!empty($search_options)){
$first_option = array_shift($search_types);
$where = " " . key($first_option) . " = " . $first_option;
foreach($search_options as $key => $option){
$where .= " AND $key = $option";
}
}
$query .= $where;