dongtangze6393 2016-02-07 20:19
浏览 53
已采纳

无论输入如何,搜索引擎的查询都会返回相同的结果

I'm writing a script for a search engine where all fields need to be able to have information submitted by themselves, or in combination with other fields. The fields are Name, City, State, ZIP, Country, Category_1. The code is below:

"SELECT * FROM table WHERE Name LIKE '%$get_name%' 
OR City LIKE '%$get_city%' 
OR State LIKE '%$get_state%' 
OR ZIP LIKE '%$get_zip%' 
OR Country LIKE '%$get_country%' 
OR Category_1 LIKE '%$get_category1%' 
LIMIT 0, 10";

If I echo all the variables, from the inputs, they all come out correct. However, the query brings up the same results regardless of what the user input was. Any suggestions? It seems to be a problem with the MYSQL query itself.

  • 写回答

1条回答 默认 最新

  • du248227 2016-02-07 20:24
    关注

    if any of the variables is empty you will get all results. its the same as Name LIKE '%%' = all results.

    You can use it this:

    $fields = array(
        'Name'  => $get_name,
        'City'  => $get_city,
        'State' => $get_state,
        'ZIP'   => $get_zip,
        'Country'   => $get_country,
        'Category_1'    => $get_category1,
    );
    
    $query = "";
    foreach($fields as $k => $data) {
        if(trim($data) != '') {
            $query .= ($query ? ' OR ' : 'WHERE ') . "$k LIKE '%% $data'";
        }
    }
    
    if($query) {
        $query = "SELECT * FROM table $query LIMIT 0, 10";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?