0

I'm working on a small FAQ site with a Searchfunction

Right now i use SQL and search for the right entry like this:

<form action="search.php" method="get">
  <label>
    Search
    <input type="text" name="keywords" autocomplete="off">
  </label>

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

<?php
require_once '../db/connect.php';

if (isset($_GET['keywords'])&& empty($_GET['keywords']) === false) {
  // code...
   $keywords = $connection->real_escape_string($_GET['keywords']);

   $query = $connection->query("
    SELECT question, answer
    FROM FAQ
    WHERE tags LIKE '%{$keywords}%'

   ");

   ?>

When i search for "WLAN" it shows the entry where i have "Wlan, Connection, ..." in the tags. When i search for Connection it shows the same entry. Great so far! But when i search for "Connection with WLAN" it doesn't work... obviously. Is there an easy method to implement this?

It would be something like '%{$keywords}%' where i can say it just has to be equal to some part of the string.

Any ideas?

Felix Kunz
  • 354
  • 2
  • 15
  • You would have to loop and add multiple `LIKE` statements. – jeroen Nov 07 '18 at 14:44
  • Don't rely on the `real_escape_string()` functions to prevent SQL injection, [they alone are not sufficient](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string). You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Nov 07 '18 at 14:44
  • What database are you using? It may have full-text search capabilities built in. – Alex Howansky Nov 07 '18 at 14:46
  • @AlexHowansky Thanks for your concern, but this site won't be accessible from the www, it's just for employees, so security wont be that much of an issue. But i'll do it if i get around . – Felix Kunz Nov 07 '18 at 14:47
  • 1
    _"so security wont be that much of an issue"_ Don't ever think that. – Alex Howansky Nov 07 '18 at 14:48
  • @AlexHowansky true... i'll do it. – Felix Kunz Nov 07 '18 at 14:51

1 Answers1

0

You can try in clause instead of like

SELECT question, answer
FROM FAQ
WHERE tags in ($keywords)

You will have to make a list of keywords which is delimited with commas and each keyword enclosed in single quotes. So split your input on space and formulate the keywords string as described.

Sam
  • 404
  • 4
  • 7