A quick and simple way to search a MySQL database. Example: MysqlSearch ('items ', 'title tags', isset ($GET ['Q'])? $GET ['Q']: '', Array ('columns '=>' * ', 'method' =>' OR ', 'extraSQL '=>' AND active = "true" ORDER BY id DESC '));
- If (! Function_exists ('MySQL _ Search ')){
- Function mysql_search ($ table, $ columns, $ query = '', $ options = Array ()){
- If (empty ($ query) {return Array ();}
- $ SQL _query = Array ();
- $ Options ['columns '] = isset ($ options ['columns'])? $ Options ['columns ']:' * ';
- $ Options ['method'] = isset ($ options ['method'])? $ Options ['method']: 'OR ';
- $ Options ['extra _ SQL '] = isset ($ options ['extra _ SQL'])? $ Options ['extra _ SQL ']: '';
- $ Query = ereg_replace ('[: <:] (and | or | the) [[: >:]]', '', $ query );
- $ Query = ereg_replace ('+', '', trim (stripslashes ($ query )));
- $ Pattern = '/([[: alpha:] +) ([[: alpha:] +) [[: alpha:]? + []? /I ';
- $ Regs = Array ();
- Preg_match_all ($ pattern, $ query, $ regs );
- $ Query = $ regs [0];
- While (list ($ key, $ value) = @ each ($ query )){
- $ Column = $ columns;
- $ Keywords = urldecode ($ value );
- If (strpos ($ value ,':')){
- $ Column = substr ($ value, 0, strpos ($ value ,':'));
- $ Keywords = trim (substr ($ keywords, strpos ($ keywords, ':') + 1 ));
- $ Keywords = ereg_replace ('\ '','', $ keywords );
- } Else {$ keywords = ereg_replace ('+', '|', $ keywords );}
- $ Column_list = explode ('', $ column );
- $ SQL = Array ();
- For ($ I = 0; $ I <count ($ column_list); $ I ++) {$ SQL [] = ''. $ column_list [$ I]. 'regexp "'. $ keywords. '"';}
- $ Query [$ key] = Array ('original' => $ value, 'SQL' => implode (''. $ options ['method']. '', $ SQL ));
- $ SQL _query = array_merge ($ SQL _query, $ SQL );
- $ SQL _query = implode (''. $ options ['method'].'', $ SQL _query );
- }
- $ Results = mysql_fetch_results (mysql_query ('select '. $ options ['columns ']. 'from '. $ table. 'Where '. $ SQL _query. ''. $ options ['extra _ SQL ']);
- Return $ results;
- }
- }
|