irwan

Simple MySQL Search Function

Nov 15th, 2011
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.15 KB | None | 0 0
  1. 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'));
  2. ======================================================================
  3.  
  4.  
  5.  
  6.  
  7.  
  8. <?php
  9.  
  10.     if (!function_exists('mysql_search')) {
  11.      
  12.     function mysql_search($table, $columns, $query = '', $options = Array()) {
  13.      
  14.     if (empty($query)) { return Array(); }
  15.      
  16.     $sql_query = Array();
  17.      
  18.     $options['columns'] = isset($options['columns'])?$options['columns']:'*';
  19.     $options['method'] = isset($options['method'])?$options['method']:'OR';
  20.     $options['extra_sql'] = isset($options['extra_sql'])?$options['extra_sql']:'';
  21.      
  22.     $query = ereg_replace('[[:<:]](and|or|the)[[:>:]]', '', $query);
  23.     $query = ereg_replace(' +', ' ', trim(stripslashes($query)));
  24.      
  25.     $pattern = '/([[:alpha:]:]+)([[:alpha:] ]+)[[:alpha:]]?+[ ]?/i';
  26.      
  27.     $regs = Array();
  28.      
  29.     preg_match_all($pattern, $query, $regs);
  30.      
  31.     $query = $regs[0];
  32.      
  33.     while (list($key, $value) = @each($query)) {
  34.      
  35.     $column = $columns;
  36.     $keywords = urldecode($value);
  37.      
  38.     if (strpos($value, ':')) {
  39.      
  40.     $column = substr($value, 0, strpos($value, ':'));
  41.     $keywords = trim(substr($keywords, strpos($keywords, ':') + 1));
  42.     $keywords = ereg_replace('\'', '', $keywords);
  43.      
  44.     } else { $keywords = ereg_replace(' +', '|', $keywords); }
  45.      
  46.     $column_list = explode(' ', $column);
  47.      
  48.     $sql = Array();
  49.      
  50.     for ($i = 0; $i < count($column_list); $i++) { $sql[] = '' . $column_list[$i] . ' REGEXP "' . $keywords . '"'; }
  51.      
  52.     $query[$key] = Array('orignal'=>$value, 'sql'=>implode(' ' . $options['method'] . ' ', $sql));
  53.      
  54.     $sql_query = array_merge($sql_query, $sql);
  55.     $sql_query = implode(' ' . $options['method'] . ' ', $sql_query);
  56.      
  57.     }
  58.      
  59.     $results = mysql_fetch_results(mysql_query('SELECT ' . $options['columns'] . ' FROM ' . $table . ' WHERE ' . $sql_query . ' ' . $options['extra_sql']));
  60.      
  61.     return $results;
  62.      
  63.     }
  64.      
  65.     }
  66. ?>
Advertisement
Add Comment
Please, Sign In to add comment