2016-03-30 124 views
-1

我想在我的網站上設置高級搜索,但是當用戶提交搜索時,如果有空字段,它會發送爲NULL。我不知道如何排除空的參數。高級搜索PHP,MySQL

下面是搜索的形式:

<form> 
    <div class="form-group"> 
    <div class="col-sm-2"> 
     <label for="Author" class="control-label">Author</label> 
    </div> 
    <div class="col-sm-10"> 
     <input type="text" class="form-control" id="author" placeholder="Author" name="author"> 
    </div> 
    </div> 
    <div class="form-group has-feedback"> 
    <div class="col-sm-2"> 
     <label for="isbn" class="control-label">ISBN</label> 
    </div> 
    <div class="col-sm-10"> 
     <input type="text" class="form-control" id="isbn" placeholder="ISBN" name="isbn"> 
    </div> 
    </div> 
    <div class="form-group"> 
    <div class="col-sm-2"> 
     <label for="genre" class="control-label">Genre</label> 
    </div> 
    <div class="col-sm-10"> 
     <input type="text" class="form-control" id="genre" placeholder="Genre" name="genre"> 
    </div> 
    </div> 
    <div class="form-group"> 
    <div class="col-sm-2"> 
     <label for="tags" class="control-label">Tags</label> 
    </div> 
    <div class="col-sm-10"> 
     <input type="text" class="form-control" id="tags" placeholder="Tags" name="tags"> 
    </div> 
    </div> 
    <div class="form-group"> 
    <div class="col-sm-2"> 
     <label for="location" class="control-label">Location</label> 
    </div> 
    <div class="col-sm-10"> 
     <input type="text" class="form-control" id="location" placeholder="Location" name="location"> 
    </div> 
    </div> 

    <div class="form-group"> 
    <div class="col-sm-offset-2 col-sm-10"> 
     <button type="submit" name="AdvancedSearch" value="Search" class="btn btn-block btn-lg btn-primary">Search</button> 

    </div> 
    </div> 
</form> 

下面是查詢:

$sql = "select * 
      from Book_info 
      where user_id=$u_id 
      AND title like '%$_REQUEST[title]%' 
      AND location like '%$_REQUEST[location]%' 
      AND author like '%$_REQUEST[author]%' 
      AND tags like '%$_REQUEST[tags]%' 
      AND genre like '%$_REQUEST[genre]%' 
      OR ISBN='$_REQUEST[isbn]'"; 

回答

0

首先,我覺得我應該對在直接注射請求的值寧願prepared statements評論到查詢字符串中。

您的問題最簡單的解決辦法是這樣的:

<?php 

$sql="select * from Book_info where user_id=$u_id"; 

$title = $_REQUEST['title']; 
$location = $_REQUEST['location']; 

if($title != null) { 
    $sql .= " AND title like '%$title%'"; 
} 

if($location != null) { 
    $sql .= " AND location like '%$location%'"; 
} 

//and so on... 

的想法是,你檢查,如果該值爲空,然後追加新的where子句來查詢,只要值不爲空(或者爲空或者其他要添加的謂詞)。