How to create filter for a search in php

时间:2017-11-25 14:06:57

标签: php mysql search filter

I have this issue with php. What I want to do, is to have a search engine with three filters: search by title, description and price. This is my index html.

<form style="text-align:center;" method="get" action="search.php">
  <label>
    Search
    <input type="text"name="keywords" autocomplete="off">
  </label>
  <input type="submit" value="Search"><br>
</form>

By using action method I'm calling search.php file.

if(isset($_GET['keywords'])) {
  $keywords = $db->escape_string($_GET['keywords']);

  $query = $db->query("SELECT title, description, price FROM products WHERE title LIKE '%{$keywords}%' OR description LIKE '%{$keywords}%' OR price LIKE '%{$keywords}%'");
}

Not it combines all of the results to one, because I'm using same variable keywords. The problem now is that I don't have a filter, because I'm not sure how to create it. Maybe I would like to have a dropdown select with those three options: title, description, price. But I don't know how to make my php code to see which one is selected. Or maybe there is a better solution for my idea? Should I use different variables like keyword was or what?

3 个答案:

答案 0 :(得分:1)

是。您必须添加一个选择以限制搜索字段:

<form style="text-align:center;" method="get" action="search.php">
  <label>
    Search
    <input type="text"name="keywords" autocomplete="off">
  </label>
<select name="field">
  <option value="title">title</option>
  <option value="description">description</option>
  <option value="prcie">price</option>
</select>

  <input type="submit" value="Search"><br>
</form>

和php:

    if(isset($_GET['keywords']) && isset($_GET['field'])) {
      $keywords = $db->escape_string($_GET['keywords']);
      $sql="SELECT title, description, price FROM products WHERE ". $_GET['field'] ." like '%{$keywords}%'" ;
      $query = $db->query($sql);
    }

此外,您必须保护您的代码不被注入。

答案 1 :(得分:1)

简单地说..添加一个选择标记。这是一个例子。

<!doctype html>
<html>
<head>
    <title>filter</title>
</head>
<body>
<form method="post" action="test1.php">
    <select name="keywords" >
    <option value="title">title</option>
    <option value="description">description</option>
    <option value="price">price</option>
    </select>
    <input type="submit">
</form>

<?php print_r($_POST); 
if(isset($_GET['keywords'])) {
  $keywords = $db->escape_string($_GET['keywords']);

  $query = $db->query("SELECT title, description, price FROM products WHERE '%{$keywords}%' LIKE '%{$keywords}%' ");
}

?>
<br>


</body>
</html>

答案 2 :(得分:1)

将输入字符串拆分为具有explode函数

的单个关键字
$keywords = "world word2";
$keywords_arr = explode(" ",$keywords);
echo $keywords_arr[0];