簡體   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