首页  >  文章  >  数据库  >  一个简单的 MySQL 搜索函数使用实例

一个简单的 MySQL 搜索函数使用实例

零下一度
零下一度原创
2017-04-25 17:48:481014浏览

怎么才能更好的学习MySQL,下面小编带你们了结一个简单的 MySQL 搜索函数。

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(&#39;[[:<:]](and|or|the)[[:>:]]&#39;, &#39;&#39;, $query);
      $query = ereg_replace(&#39; +&#39;, &#39; &#39;, trim(stripslashes($query)));
      $pattern = &#39;/([[:alpha:]:]+)([[:alpha:] ]+)[[:alpha:]]?+[ ]?/i&#39;;
      $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, &#39;:&#39;)) {
            $column = substr($value, 0, strpos($value, &#39;:&#39;));
            $keywords = trim(substr($keywords, strpos($keywords, &#39;:&#39;) + 1));
            $keywords = ereg_replace(&#39;\&#39;&#39;, &#39;&#39;, $keywords);
         } else { $keywords = ereg_replace(&#39; +&#39;, &#39;|&#39;, $keywords); }
         $column_list = explode(&#39; &#39;, $column);
         $sql = Array();
         for ($i = 0; $i < count($column_list); $i++) { $sql[] = &#39;&#39; . $column_list[$i] . &#39; REGEXP "&#39; . $keywords . &#39;"&#39;; }
         $query[$key] = Array(&#39;orignal&#39;=>$value, &#39;sql&#39;=>implode(&#39; &#39; . $options[&#39;method&#39;] . &#39; &#39;, $sql));
         $sql_query = array_merge($sql_query, $sql);
         $sql_query = implode(&#39; &#39; . $options[&#39;method&#39;] . &#39; &#39;, $sql_query);
      }
      $results = mysql_fetch_results(mysql_query(&#39;SELECT &#39; . $options[&#39;columns&#39;] . &#39; FROM &#39; . $table . &#39; WHERE &#39; . $sql_query . &#39; &#39; . $options[&#39;extra_sql&#39;]));
      return $results;
   }

}

以上是一个简单的 MySQL 搜索函数使用实例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn