Build a php search with myql
Sunday, January 6th, 2008So this is big. Most company want a very indepth search on there website, so what do you do. Well most people just do a simple SQL query with the like operator in there. However search is much much more than that. Several things to take in account are stop words, relevancy, uppercase/lowercase, trimming, multiple words, and so much more. Hopefully this will help you a little.
Things to remember
- Never run the user supplied information straight to the database
- Trim off the extra spaces
- Convert to lower case
- Clean out stop words like: ‘and’, ‘if’, ‘or’……
- Strip out punctuation
To start:
1 2 3 4 5 6 7 8 9 | //Make this bigger for what you need
$stop_words = array(" if", " and ", " other ", " dont ", " never ");
$punctuation = array('/','\\','\'','<','>','(','*','&','?',';',':','[',']','{','}','|'
,'=','+','"',',','.','-','_',')','^','%','$','#','@','!','~','`');
$string = strtolower($_GET['search']);
$string = str_replace($stop_words, ' ',$string);
$string = str_replace($punctuation, ' ',$string);
$string = trim($string); |
Porter Stemming Algorithm
Check this out, Porter Stemming Alorithm. You should become acquainted with this algorithm if u want to build a great search. Basically every word has multiple variations, and what you want to do it dumb down all words to there basic.
For example: The word ‘Visual’ can also be Visuals, Visualization. If you just do a basic search and type Visualization, things like visual wont show up. What do you do? Well download a class that applies this algorith to your string.
This article is still being written
What Now?!
Now is time to think. Go figure. So on to the actual query. You can write it with a simple query like this:
1 | $sql = "select * from table where column like '%$string%';" |
The only problem with that is the search is gonna have to be near exact, so what you need to do is search with an or and split the string by words.
1 | $sql = "select * from table where (column like '%$word1%' or column like '%$word2%');" |
So now you have all these results.. Now is the hard part and the part i leave you at. Your gonna have to write an algorithim or a means of reordering the list. Some things to remember. More exact results should show up higher on the list.
Author: Jason Rogers
Welcome to Neurotic Geeks a personal blog about a flourishing programmer (Jason Rogers) in the web industry. You'll experience many a wonder while visiting. Oh, and i love guitar.




