繁体   English   中英

在php和mysql中进行更好的搜索查询

[英]making a better search query in php and mysql

我正在尝试创建搜索查询:

我给了6个搜索选项。

  1. 卧室
  2. 类型
  3. 邮编
  4. 位置
  5. 最低价格
  6. 最高价格

我在表格中有这些字段。 我搜索了很多但找不到我正在搜索的答案。 我也尝试使用LIKE%查询。 但这也没有成功。

如果用户仅选择“类型”,则应显示该类型的所有数据。 其他领域也是如此。

同样,如果用户选择2或3个选项并进行搜索,则应显示与所选选项匹配的结果。

如何创建这样的搜索? 我该怎么办?:

if(){

}else if(){

}

动态构建查询

$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 (...)

}

您可以动态构建您的SQL查询。 如果搜索值不为空(或其他不计入搜索值的内容),则不要添加搜索。 不要忘记将mysql_real_escape_string添加到params或者坏人会利用你的软件。

例如:

<?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来做db选择。

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM