当前位置:Gxlcms > PHP教程 > 简单的MySQL搜索函数

简单的MySQL搜索函数

时间:2021-07-01 10:21:17 帮助过:3人阅读

A quick and simple way to search a MySQL database.
示例:
mysqlsearch('items', 'title tags', isset($GET['q'])?$GET['q']:'', Array('columns'=>'*', 'method'=>'OR', 'extrasql'=>'AND active = "true" ORDER BY id DESC'));
  1. if (!function_exists('mysql_search')) {
  2. function mysql_search($table, $columns, $query = '', $options = Array()) {
  3. if (empty($query)) { return Array(); }
  4. $sql_query = Array();
  5. $options['columns'] = isset($options['columns'])?$options['columns']:'*';
  6. $options['method'] = isset($options['method'])?$options['method']:'OR';
  7. $options['extra_sql'] = isset($options['extra_sql'])?$options['extra_sql']:'';
  8. $query = ereg_replace('[[:<:]](and|or|the)[[:>:]]', '', $query);
  9. $query = ereg_replace(' +', ' ', trim(stripslashes($query)));
  10. $pattern = '/([[:alpha:]:]+)([[:alpha:] ]+)[[:alpha:]]?+[ ]?/i';
  11. $regs = Array();
  12. preg_match_all($pattern, $query, $regs);
  13. $query = $regs[0];
  14. while (list($key, $value) = @each($query)) {
  15. $column = $columns;
  16. $keywords = urldecode($value);
  17. if (strpos($value, ':')) {
  18. $column = substr($value, 0, strpos($value, ':'));
  19. $keywords = trim(substr($keywords, strpos($keywords, ':') + 1));
  20. $keywords = ereg_replace('\'', '', $keywords);
  21. } else { $keywords = ereg_replace(' +', '|', $keywords); }
  22. $column_list = explode(' ', $column);
  23. $sql = Array();
  24. for ($i = 0; $i < count($column_list); $i++) { $sql[] = '' . $column_list[$i] . ' REGEXP "' . $keywords . '"'; }
  25. $query[$key] = Array('orignal'=>$value, 'sql'=>implode(' ' . $options['method'] . ' ', $sql));
  26. $sql_query = array_merge($sql_query, $sql);
  27. $sql_query = implode(' ' . $options['method'] . ' ', $sql_query);
  28. }
  29. $results = mysql_fetch_results(mysql_query('SELECT ' . $options['columns'] . ' FROM ' . $table . ' WHERE ' . $sql_query . ' ' . $options['extra_sql']));
  30. return $results;
  31. }
  32. }

人气教程排行