【问题标题】:Advanced Search PHP, MySQL高级搜索 PHP、MySQL
【发布时间】:2016-03-30 01:48:48
【问题描述】:

我正在尝试在我的网站上设置高级搜索,但是当用户提交他们的搜索时,如果有一个空字段,它将作为 NULL 发送。我不确定如何排除空参数。

下面是搜索表格:

<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]'";

【问题讨论】:

    标签: php mysql advanced-search


    【解决方案1】:

    首先,我觉得我应该评论一下我更喜欢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 子句附加到您的查询中,只要该值不为空(或为空或您要添加的任何其他谓词)。

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多