龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php 简单的 MySQL 搜索函数

时间:2014-07-28 11:06来源:网络整理 作者:网络 点击:
分享到:
简单的 MySQL 搜索函数 A quick and simple way to search a MySQL database.示例:mysql _search(#39;items#39;, #39;title tags#39;, isset($_ GET[#39;q#39;])?$ _GET[#39;q#39;]:#39;#39;,Array(#39;columns#39;=gt;#39;*#39;, #39;method#39;=gt;

A quick and simple way to search a MySQL database.

示例:

mysql search('items', 'title tags', isset($ GET['q'])?$ GET['q']:'', Array('columns'=>'*', 'method'=>'OR', 'extra sql'=>'AND active = "true" ORDER BY id DESC'));

if (!function_exists('mysql_search')) {

   function mysql_search($table, $columns, $query = '', $options = Array()) {

      if (empty($query)) { return Array(); }

      $sql_query = Array();

      $options['columns'] = isset($options['columns'])?$options['columns']:'*';
      $options['method'] = isset($options['method'])?$options['method']:'OR';
      $options['extra_sql'] = isset($options['extra_sql'])?$options['extra_sql']:'';

      $query = ereg_replace('[[:<:]](and|or|the)[[:>:]]', '', $query);
      $query = ereg_replace(' +', ' ', trim(stripslashes($query)));

      $pattern = '/([[:alpha:]:]+)([[:alpha:] ]+)[[:alpha:]]?+[ ]?/i';

      $regs = Array();

      preg_match_all($pattern, $query, $regs);

      $query = $regs[0];

      while (list($key, $value) = @each($query)) {

         $column = $columns;
         $keywords = urldecode($value);

         if (strpos($value, ':')) {

            $column = substr($value, 0, strpos($value, ':'));
            $keywords = trim(substr($keywords, strpos($keywords, ':') + 1));
            $keywords = ereg_replace('\\'', '', $keywords);

         } else { $keywords = ereg_replace(' +', '|', $keywords); }

         $column_list = explode(' ', $column);

         $sql = Array();

         for ($i = 0; $i < count($column_list); $i++) { $sql[] = '' . $column_list[$i] . ' REGEXP "' . $keywords . '"'; }

         $query[$key] = Array('orignal'=>$value, 'sql'=>implode(' ' . $options['method'] . ' ', $sql));

         $sql_query = array_merge($sql_query, $sql);
         $sql_query = implode(' ' . $options['method'] . ' ', $sql_query);

      }

      $results = mysql_fetch_results(mysql_query('SELECT ' . $options['columns'] . ' FROM ' . $table . ' WHERE ' . $sql_query . ' ' . $options['extra_sql']));

      return $results;

   }

}
//该片段来自于http://outofmemory.cn
精彩图集

赞助商链接