首页 > 后端开发 > php教程 > 简单的 MySQL 搜索函数

简单的 MySQL 搜索函数

WBOY
发布: 2016-07-25 09:11:13
原创
1022 人浏览过
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. }
复制代码


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板