Simple MySQL Search


/ Published in: PHP
Save to your folder(s)

A quick and simple way to search a MySQL database. Example: mysql_search('items', 'title tags', isset($_GET['q'])?$_GET['q']:'', Array('columns'=>'*', 'method'=>'OR', 'extra_sql'=>'AND active = "true" ORDER BY id DESC'));


Copy this code and paste it in your HTML
  1. if (!function_exists('mysql_search')) {
  2.  
  3. function mysql_search($table, $columns, $query = '', $options = Array()) {
  4.  
  5. if (empty($query)) { return Array(); }
  6.  
  7. $sql_query = Array();
  8.  
  9. $options['columns'] = isset($options['columns'])?$options['columns']:'*';
  10. $options['method'] = isset($options['method'])?$options['method']:'OR';
  11. $options['extra_sql'] = isset($options['extra_sql'])?$options['extra_sql']:'';
  12.  
  13. $query = ereg_replace('[[:<:]](and|or|the)[[:>:]]', '', $query);
  14. $query = ereg_replace(' +', ' ', trim(stripslashes($query)));
  15.  
  16. $pattern = '/([[:alpha:]:]+)([[:alpha:] ]+)[[:alpha:]]?+[ ]?/i';
  17.  
  18. $regs = Array();
  19.  
  20. preg_match_all($pattern, $query, $regs);
  21.  
  22. $query = $regs[0];
  23.  
  24. while (list($key, $value) = @each($query)) {
  25.  
  26. $column = $columns;
  27. $keywords = urldecode($value);
  28.  
  29. if (strpos($value, ':')) {
  30.  
  31. $column = substr($value, 0, strpos($value, ':'));
  32. $keywords = trim(substr($keywords, strpos($keywords, ':') + 1));
  33. $keywords = ereg_replace('\'', '', $keywords);
  34.  
  35. } else { $keywords = ereg_replace(' +', '|', $keywords); }
  36.  
  37. $column_list = explode(' ', $column);
  38.  
  39. $sql = Array();
  40.  
  41. for ($i = 0; $i < count($column_list); $i++) { $sql[] = '' . $column_list[$i] . ' REGEXP "' . $keywords . '"'; }
  42.  
  43. $query[$key] = Array('orignal'=>$value, 'sql'=>implode(' ' . $options['method'] . ' ', $sql));
  44.  
  45. $sql_query = array_merge($sql_query, $sql);
  46. $sql_query = implode(' ' . $options['method'] . ' ', $sql_query);
  47.  
  48. }
  49.  
  50. $results = mysql_fetch_results(mysql_query('SELECT ' . $options['columns'] . ' FROM ' . $table . ' WHERE ' . $sql_query . ' ' . $options['extra_sql']));
  51.  
  52. return $results;
  53.  
  54. }
  55.  
  56. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.