I ajax模糊搜索(mysql方式查询)

很多地方会用到模糊搜索,这里采用的是iconv_substr方法,截取字符串进行匹配实现搜索功能
getdata.php



    header("Content-type:text/html;charset=gbk");
    //数据库配置信息(用户名,密码,数据库名,表前缀等)
    $cfg_dbhost = "localhost";
    $cfg_dbuser =  "root";
    $cfg_dbpwd = "Wanda2013";
    $cfg_dbname = "ajaxtest";
    $cfg_dbprefix = "";

    $link = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd);
    mysql_select_db($cfg_dbname);
    mysql_query("set names gbk");
    //防止乱码
    $keywords = iconv("utf-8","gbk//IGNORE",$_POST['keywords']);
    //匹配输入的关键字相关的标题,并按点击量排名,点击越多的排最前面
    $sql = "select title from ".$cfg_dbprefix."article where title like '%".$keywords."%' order by click desc limit 0,9;";
    //echo $sql;
    $res = mysql_query($sql,$link);

    $mNums = mysql_num_rows($res);
    //echo $mNums;
    $row=mysql_fetch_array($res);
    if($mNums<1){
        echo "no";
        exit();
    }else if($mNums==1){
        //返回json数据
        echo "[{'keywords':'".iconv_substr($row['title'],0,14,"gbk")."'}]";
    }else{
        $result="[{'keywords':'".iconv_substr($row['title'],0,14,"gbk")."'}";
        while($row=mysql_fetch_array($res)){
            $result.=",{'keywords':'".iconv_substr($row['title'],0,14,"gbk")."'}";
        }
        $result.=']';
        echo $result;
    }
    mysql_free_result($res);

?>

deal.php



    header("Content-type:text/html;charset=utf-8");
    $keywords = $_GET['keywords'];
    echo "您本次搜索的关键词是:".$keywords."";

?>

index.html


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>searchSuggesttitle>
<link href="css/searchSuggest.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js">script>
<script type="text/javascript" src="js/searchSuggest.js">script>
head>

<body>
<div id="searchSuggest">
    <form action="deal.php" method="get" id="suggest_form">
        <input type="text" name="keywords" id="suggest_input" autocomplete="off"/>
        <input type="submit" value="搜索一下" id="suggest_submit" />
    form>
    <ul id="suggest_ul">
    ul>
div>

body>
html>

数据库设计

DROP TABLE IF EXISTS `article`;
CREATE TABLE `article` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(64) NOT NULL,
  `click` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `title` (`title`)
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=gbk;

demo下载:
http://pan.baidu.com/s/1c2vL3Mw

你可能感兴趣的:(PHP代码积累)