Simple MySQL search function

WBOY
Release: 2016-07-25 09:11:13
Original
988 people have browsed it
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. }
复制代码


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template