如何基于多个参数进行搜索

时间:2017-04-05 08:55:23

标签: php sqlsrv

我的搜索查询有问题。我尝试根据用户输入搜索数据库,并限制他们查看某些详细信息,但它无法正常工作。我做错了什么?

这是我的查询:

if(isset($_GET['search_term']))
{


    $search_term = $_GET['search_term'];
    $ind = 'IND';
    if(empty($search_term)){
     echo '<div class="alert-warning" id="alert_message">Error: enter your query parameter.</div>'; 
    }else{

     $query = "SELECT * FROM [info].[dbo].[customer] WHERE cust_no LIKE '%$search_term'  OR branch LIKE $search_term AND cust_type != 'BUS' AND cust_type != 'GRP' AND cust_type != 'MGM' AND cust_type != 'INT'" ;
   $check = sqlsrv_query($conn, $query);  

   #checks if the search was made
                        if($check == false){
                             die( print_r( sqlsrv_errors(), true));
                        }

                        #checks if the search brought some row and if it is one only row
                        if(sqlsrv_has_rows($check) != 1){
                               echo '<div class="alert-warning" id="alert_message">Error: no data found for this query.</div>';


                        }

3 个答案:

答案 0 :(得分:0)

您不应该将ORAND组合在一起,它不会达到预期效果并且可以匹配更多。

你可能想要这样的东西:

SELECT * FROM [info].[dbo].[customer] WHERE 
  (cust_no LIKE '%$search_term' OR branch LIKE $search_term)  // are these conditions even valid sql?
  AND cust_type != 'BUS' 
  AND cust_type != 'GRP' 
  AND cust_type != 'MGM' 
  AND cust_type != 'INT'

注意:您还应该查看准备好的语句,以摆脱现在的SQL注入问题。

答案 1 :(得分:0)

试试这个:

SELECT 
  * 
FROM
  [ info ] .[ dbo ] .[ customer ] 
WHERE (
    cust_no LIKE '%sss%' 
    OR branch LIKE '%sss%'
  ) 
  AND cust_type != 'BUS' 
  AND cust_type != 'GRP' 
  AND cust_type != 'MGM' 
  AND cust_type != 'INT' 

答案 2 :(得分:0)

试试这个

$query = "SELECT * FROM [info].[dbo].[customer] WHERE cust_no LIKE '". %$search_term ."'  OR branch LIKE  '". %$search_term% ."' AND cust_type != 'BUS' AND cust_type != 'GRP' AND cust_type != 'MGM' AND cust_type != 'INT'" ;