mysql SELECT LIKE must match whole words only to the variable

mysql, php

Solution

If you want full word matching you should consider trying FULLTEXT searching. One prerequisite is that your table must be using the MyISAM engine:

CREATE TABLE test (
  id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  headline VARCHAR(120) NOT NULL,
  description VARCHAR(255) NOT NULL,
  FULLTEXT(headline, description)
) ENGINE=MyISAM;

You would query for matches like so:

SELECT *
FROM test
WHERE MATCH (headline,description) AGAINST('$string');

This has the added benefit of ordering your results by relevancy.

Problem

I have a $string variable, and I use ``` SELECT * FROM db WHERE description LIKE '%$string%' OR headline LIKE '%$string%' ``` As seen, I want to search the two fields "description" and "headline" to see if the string variable matches any of them. Problem is that I want it to match whole words!!! Ex: If description contains "hello", It is enough if $string is an 'h'. this is not what I want.It has to match the whole word only! I split the querystring into words for this? or what?

Original source