Home > Database > Mysql Tutorial > A simple MySQL search function usage example

A simple MySQL search function usage example

零下一度
Release: 2017-04-25 17:48:48
Original
1046 people have browsed it

How to learn MySQL better, the editor below will show you a simple MySQL search function.

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;
   }

}
Copy after login

The above is the detailed content of A simple MySQL search function usage example. For more information, please follow other related articles on the PHP Chinese website!

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