首頁 >後端開發 >php教程 >簡單的 MySQL 搜尋函數

簡單的 MySQL 搜尋函數

WBOY
WBOY原創
2016-07-25 09:11:131018瀏覽
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. }
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:PHP+MYSQL翻頁符下一篇:PHP+MYSQL翻頁符