views:

100

answers:

3

I asked this question about a year ago on another site but never got the answers I was looking for. And I've been wondering about it ever since.

I'd like to impliment some search functions similar to Google's (inurl:foo, site:bar.com)

So if you entered a normal query, with none of these functions included, it would search one column.

However if you included a function (func:foo bar) it would search column 1 for foo and column 2 for bar.

What's a good solution for this in PHP and MySQL. Also, multiple functions (func1:foo func2:bar query) would be good too.

+1  A: 

I dont think there is a direct way to do that, but you can write a script. Your script first parse the search query and find special occurences, something like this:

preg_match_all("/([\w_]+):([\w_]+)/", $search_query);

Then you have special requests for your search, say your user asked for user:marvin tag:php comment:preg. Then you know with above regular expression that your user wants to see the comments or marvin tagged as php and includes the term preg and you can build your sql statement accordingly.

marvin
A: 

I believe you need a full-text search library. Lucene is a good one. Zend Search Lucene is a port of Lucene to PHP. Solr is a relatively easy way to get much of Lucene's functionality. Sphinx is an alternative tool known for its easy integration with MySQL.

Yuval F
A: 

If you have the function values stored in columns already, then it should be possible to do this by building up the appropriate SQL query (in Python, but should be easily convertible to PHP):

functions = ['func1', 'func2', ...]
clauses = []
for term in search_query.split():
    if ':' in term:
        func, value = term.split(':', 1)
        if func in functions:
            clauses.append('%s=%s' % (func, value))
            continue
    clauses.append('column LIKE %s' % result)


# The following is vulnerable to SQL injection, so don't do it.  A
# better way would be to use prepared statements.
sql = 'SELECT result FROM search_table WHERE ' + ' AND '.join(clauses)

You can get a lot fancier by being more clever with the query, but the general idea should be the same.

Zach Hirsch