1

I have a input field that search's for keywords in my database. Say the title of a car listing is "Toyota surf 1990 SSR-X", I want to be able to search something like "Toyota 1990", how can I achieve this?. If I search "Toyota surf" or "surf 1990" it works.

$query = "SELECT * FROM cars WHERE title LIKE '%" . $search_keywords . "%'";
vhu
  • 11,219
  • 11
  • 35
  • 42
Gian
  • 31
  • 4
  • 1
    Look into fulltext search – John Conde Sep 13 '15 at 20:47
  • well if year,make,model, etc are columns in that table(which would make sense for a table called cars?), you can build your where clause dynamically like: `WHERE make = 'Toyota' AND model = 'Surf'` or `WHERE model = 'surf' AND year = '1990'` –  Sep 14 '15 at 00:45
  • Notice: Your code is vulnerable to [SQL injections](http://stackoverflow.com/q/601300/3440545). [Always sanitize your database inputs](http://xkcd.com/327/) – AbcAeffchen Sep 14 '15 at 11:06

1 Answers1

3

$query = "SELECT * FROM cars WHERE title LIKE '%" . $search_keywords . "%'";

That code used in MySQL, so it doesn't have any relates with the main PHP coding.

Try using the preg_match feature instead. Here is an example:

preg_match("KEYWORDS", $variable)

And you could add an if statement. Like the following:

if(preg_match("KEYWORDS", $variable))

I wish I could give you the solution that you are requesting for.

Themud
  • 58
  • 1
  • 9