欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

简单的 MySQL 搜索函数

程序员文章站 2022-05-29 08:57:19
...
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('[[:<:>:]]', '', $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
  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. }
复制代码