简体   繁体   中英

How to create filter for a search in php

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?

Yes. You have to add a select to limit field of search:

<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>

and 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);
    }

Besides You have to protect your code from injection.

that's ver simple.. add a select tag. here's an example.

<!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>

Split the input string to single keywords with explode function

$keywords = "world word2";
$keywords_arr = explode(" ",$keywords);
echo $keywords_arr[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM