【问题标题】:Advanced search with ajax, php and mysql使用 ajax、php 和 mysql 进行高级搜索
【发布时间】:2017-03-23 19:15:17
【问题描述】:

我正在使用 ajax、php 和 mysql 构建高级搜索。下面是搜索表单 (html)、AJAX 调用和处理请求的 php 脚本的工作代码。但是,我面临的问题是如何进行动态 mysql 查询。

例如,如果用户在搜索输入中搜索“Hilton Hotel”,则选择“accommodation”作为industry_types,选择“Hotel”作为sub_industry_type,并选择“London”作为城市。如何编写一个将所有这些输入都考虑在内的查询?

请注意:在 search.php 中,我包含了用于处理 user_search_input 输入中提交的关键字的查询。

Index.php (HTML):

<form class="user_search_form" action="" method="post"> 
<input type="text" class="user_search_input" placeholder="search" />    

<select class="industry_types" name="industry_types" id="industry_types">
<option value="">Select an industry</option>
<option value="Accommodation">Accommodation</option>
<option value="Food_Drink">Food & Drink</option>
<option value="Entertainment">Entertainment</option>
<option value="Retail">Retail</option>      
<option value="Telecommunications">Telecommunications</option>  
<option value="Transportation">Transportation</option>      
</select>   


<select class="Accommodation sub_industry_type" name="Accommodation" id="sub_industry_type">
<option value="0">Select Accommodation subcategory</option>
<option value="Bed and Breakfasts">Bed and Breakfasts</option>
<option value="Hotel">Hotels</option>
<option value="Hotel">Hostels</option>
<option value="Resturant">Resorts</option>
<option value="Serviced apartments">Serviced apartments</option>
</select>

<select class="Food_Drink sub_industry_type" name="Food_Drink" id="sub_industry_type">
<option value="0">Select Cuisine subcategory</option>
<option value="Resturant">Restaurants</option>
<option value="Cafes">Cafes</option>
<option value="Bars and Pubs">Bars and Pubs</option>
<option value="Tourist Agency">Night clubs</option>
</select>   


<select class="Entertainment sub_industry_type" name="Entertainment" id="sub_industry_type">
<option value="0">Select Entertainment subcategory</option>
<option value="Performing Arts">Performing Arts</option>
<option value="Cinemas">Cinemas</option>
<option value="Resorts and Casinos">Resorts and Casinos</option>
<option value="Amusement Parks and Attractions">Amusement Parks</option>    
<option value="Museums">Museums</option>
<option value="Outdoor activities">Outdoor activities</option>
<option value="Media and Entertainment Other">Entertainment Other</option>
</select>

<select class="Retail sub_industry_type" name="Retail" id="sub_industry_type">
<option value="0">Select Retail subcategory</option>        
<option value="Beer, Wine and Liquor Stores">Beer, Wine and Liquor Shops</option>
<option value="Clothing and Shoe Stores">Clothing and Shoe Shops</option>
<option value="Electronic Shops">Electronic Shops </option>
<option value="Jewelry, Luggage, and Accessories">Jewelry, Luggage, and Accessories</option>
<option value="Sporting Goods, Hobby, Books and Music Stores">Sporting Goods, Hobby, Books and Music Stores</option>
<option value="Internet Businesses">Internet Businesses</option>    
<option value="Retail Others">Retail Others</option>
</select>

<select class="Telecommunications sub_industry_type" name="Telecommunications" id="sub_industry_type">
<option value="0">Select Telecommunications subcategory</option>    
<option value="Telephone Service Providers and Carriers">Telephone Service Providers</option>
<option value="Telecommunications Other">Telecommunications Other</option>
</select>       

<select class="Transportation sub_industry_type" name="Transportation" id="sub_industry_type">
<option value="0">Select Transportation subcategory</option>    
<option value="Car Rental">Car Rentals</option>
<option value="Taxi, Buses and Transit Systems">Taxi Services</option>
<option value="Travel Agents">Travel Agents</option>    
</select>               

<select name="select_city" class="select_city">
<option value="">City</option>
<option value="">London</option>
<option value="">New York</option>
<option value="">Paris</option>
</select>

<input type="submit" value="search"  class="search_btn" />  
</form> 

Index.php (AJAX):

$('.user_search_form').submit(function(e){
 e.preventDefault();    

var $search_input = $('.user_search_input').val();  
var $industry_general = $('.industry_types').val(); 
var $industry_spesific = $('.sub_industry_type').val(); 
var $selected_city = $('.select_city').val();   


var url = "search.php"; 

        $.ajax({    //create an ajax request to load_page.php
        type: "POST", 
        url: url, 
        data:{search_input: $search_input, industry_general: $industry_general, industry_spesific: $industry_spesific, selected_city: $selected_city},  
        dataType: "html",   //expect html to be returned                
        success: function(date){                    
        $('#search_results').html(date); 


        }
    })
});     

search.php(问题):

<?php include 'includes/db_connect.php'; 

$search_input = $_POST['search_input'];
$industry_general = $_POST['industry_general'];
$industry_spesific = $_POST['industry_spesific'];
$selected_city = $_POST['selected_city'];

if(!empty($search_input)){

$sql = $dbh->prepare("SELECT * FROM table WHERE company_name LIKE :company_name OR company_keywords LIKE :company_keywords OR company_city LIKE :company_city OR company_email LIKE :company_email");

    $sql->bindValue(':company_name', '%' . $search_input . '%', PDO::PARAM_STR);    
    $sql->bindValue(':company_keywords', '%' . $search_input . '%', PDO::PARAM_STR);    
    $sql->bindValue(':company_city', '%' . $search_input . '%', PDO::PARAM_STR);    
    $sql->bindValue(':company_email', '%' . $search_input . '%', PDO::PARAM_STR);   


    if($sql->execute()) {
       $sql->setFetchMode(PDO::FETCH_ASSOC);
    }   

}

elseif(!empty($industry_general)){

           // if industry_general is not empty   
}

elseif(!empty($industry_spesific)){

          // if industry_spesific is not empty      
}

elseif(!empty($selected_city)){

         // if selected_city is not empty 
}?>

【问题讨论】:

  • 动态是什么意思?你的代码看起来不错。
  • 这里有很多不必要的代码。无论如何,我无法真正帮助您解决您的问题。
  • @learner 我的代码很好。一切正常,但我不知道从这里去哪里。当我说动态时,如果您查看 php 文件,下一个查询是什么?这将影响第一个结果。然后是第三、第四。这就是让我困惑的地方。
  • 在构建所有逻辑操作后做准备语句。例如:制作一些字符串变量 $sql。然后,如果某些条件对这些 $sql 进行连接。最后准备并执行您的查询
  • @EvanCarslake 那为什么要说什么?你说得对,有很多不必要的代码,我只是想给出一个完整的图片。

标签: php mysql ajax advanced-search


【解决方案1】:

这个sn-p怎么样?

// columns that should contain either of the search_input words
$searchTermCols = [
    'company_name',
    'company_keywords',
    'company_city',
    'company_email'
];

$data = $_POST; // copy $_POST array to a variable so you can safely alter keys/values
$searchInput = $data['search_input']; // tmp store search_input so you can unset it for the rest of the code
unset($data['search_input']); // unset unnecessary keys (if you have any). like in your case you want to do different stuff with that key=>value
//unset($data['some_other_unwanted_input_doing_other_stuff']); // or another one
$searchInputParts = preg_split('/\s+/', $searchInput); // explode by whitespace
$searchInput = implode('|',$searchInputParts); // for REGEXP search in mysql to search each word occurrence in a column

foreach($data as $key=>$val) { // loop through copied array
    $sqlParts1[] = $key.' LIKE :'.$key;
}
foreach($searchTermCols as $key) { // loop through columns that should contain either of the words
    $sqlParts2[] = $key.' REGEXP :'.$key;
}

$andParts = implode(' AND ',$sqlParts1); // these options must exists in the columns
$orParts = implode(' OR ',$sqlParts2); // these options must exists in the columns

$qryStr = "SELECT * FROM table WHERE ";
$qryStr .= "($andParts) AND ($orParts)"; // concatenate both similar but different queries and append to query
$sql = $dbh->prepare($qryStr);

foreach($data as $key=>$val) {
    $sql->bindValue(':'.$key, '%' . trim($val) . '%', PDO::PARAM_STR);
}
foreach($searchTermCols as $key) {
    $sql->bindValue(':'.$key, $searchInput, PDO::PARAM_STR);
}

if($sql->execute()) {
    $sql->setFetchMode(PDO::FETCH_ASSOC);
}

更新

您可以将 $_POST 复制到另一个变量并取消设置查询中不需要的键。查看前两行添加的代码和设置为循环的 $data 变量。

更新 2 重要..

您的表单输入的名称属性需要与您的数据库表的列相匹配。比如:

<input type="text" name="company_name" id="company_name">

如果您的 db 表的列名是“company_name”。

更新 3

为了好玩,我添加了您评论中解释的要求。我没有你的表结构所以我没有测试它......

【讨论】:

  • 我得到响应:“Column not found: 1054 Unknown column 'search_input'”,我喜欢这段代码,它很简单但很复杂。
  • 我认为这是因为我在 ajax 调用中分别传递了元素值。
  • 这取决于你想用search_input的值做什么。如我的答案编辑中所示,您可以将其从 foreach 循环中排除。但也许你可以解释一下你想用 search_input 做什么。
  • 所以我只需添加与发布变量一样多的$data = $_POST; unset($data['search_input']);
  • search_input 正在根据用户输入的关键字搜索数据库。
猜你喜欢
  • 2017-06-02
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
相关资源
最近更新 更多