怎么才能更好的学习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('[[:<:]](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;
}
}
以上就是一个简单的 mysql 搜索函数使用实例的详细内容。