I’ve been trying to re-write some code to implement a search function in a php app I put together. I can’t quite get it & I’m sure its something simple. If anyone wants to take a look and tell me what stupid little mistake I made I would appreciate it.
You can see the code in the pastebin link below
http://christer.pastebin.com/668595
(yes, this means you openclue.org readers. Who else reads our blogs? honestly?)
I’ve been meaning to do a simple search like that myself someday .. haven’t gotten around to it yet. You seem to be on the right track though.
Couple of things you may want to look into, though. If you are using MySQL + MyISAM you could always turn on a fulltext index search on the column you’re searching off of, and then use some functions to search with it. One advantage is that will turn on stop words that it won’t search for — stuff like and, or, if, etc.
As far splitting it up, I’d use a preg_split instead of explode, personally. Either one would do the job though.
$search_vars = preg_split(‘/\s/’, $search_string);
foreach($search_vars as $value) {
$arr[] = ” name LIKE (%”.mysql_escape_string($value).”%) “;
}
$implode = implode(‘ OR ‘, $arr);
if(count($arr)) > 0)
$sql_search = “SELECT name FROM table WHERE $implode ORDER BY name;”;
Something like that, for a basic search. If you want better results though, like I said, look at fulltext searching.
http://www.zend.com/zend/tut/tutorial-ferrara1.php