【问题标题】:making a better search query in php and mysql在 php 和 mysql 中进行更好的搜索查询
【发布时间】:2013-07-14 14:57:18
【问题描述】:

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

我提供了 6 个搜索选项。

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

我在表单中有这些字段。我搜索了很多,但找不到我正在搜索的答案。我也尝试使用LIKE% 进行查询。但这也没有奏效。

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

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

如何创建这样的搜索?我应该这样做吗?:

if(){

}else if(){

}

【问题讨论】:

  • 通过“同样,如果用户选择 2 或 3 个选项并进行搜索,则应显示与所选选项匹配的结果。”你的意思是当用户给出 2 到 3 个选项时,它将被搜索为“OR”还是“AND”
  • 你不能相对于选项创建你的sql语句吗?类似于: if ($type) { $sql .= ' AND Type = :type'; } 等等等等...
  • 你的相关表结构是什么?
  • @saranbanerjee 它应该是 AND
  • @Rpg600 我可以,但你能举个例子吗

标签: php mysql search multiple-columns


【解决方案1】:

您可以即时构建您的 sql 查询。如果搜索值不为空(或不计为搜索值的其他内容),则不要添加搜索。 不要忘记将 mysql_real_escape_string 添加到参数中,否则坏人会利用您的软件。

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 进行数据库选择。

【讨论】:

    【解决方案2】:

    动态构建查询

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

    【讨论】:

      【解决方案3】:
      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        • 2012-11-12
        • 2011-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多