Reputation: 7906
I have a search text field which searches a particular column in a table, but the results are not as I expected.
When the user tries to search like "hello world how", he will not find a result as I the query is LIKE '%hello world how%'. The table row contains the string "hello world".
How do I do a proper search using php and mysql, and what if I need to do a search on multiple tables/ all columns in a table? Which is the best way to do it?
Upvotes: 1
Views: 128
Reputation: 51411
One bad way to do this would be to split the user's search text on whitespace. "hello world how" would become "hello%world%how". However, this still would require the word "how" to be in there, after "hello world", and would not guarantee that "hello" and "world" are near each other.
Further, even if you've put an index on the column being searched, a LIKE clause that stars with a wildcard character (%) can not use that index in MySQL. This means that every search would be a full table scan. That can get pretty slow.
One solution for you might be MySQL fulltext search. It's pretty flexible. However, it only works with MyISAM tables. You probably want to use InnoDB for your data, because MyISAM does not support foreign keys or transactions. You can create separate, dedicated tables that use MyISAM and fulltext indexing, just for searching purposes.
Sphinx is another option available to you. It's a third party search system that can be attached to MySQL and PHP.
All of these answers, however, are focused around searching one column at a time. If you need to search entire rows, that becomes a little more interesting. You might want to consider a "document"-based search system, like ElasticSearch.
Upvotes: 2