Home > php教程 > php手册 > php站内搜索并高亮显示关键字的实现代码

php站内搜索并高亮显示关键字的实现代码

WBOY
Release: 2016-06-06 20:39:37
Original
1372 people have browsed it

将sql语句中包含的%$info%交给DBMS执行的时候,他会查找字段中含有变量$info的值的信息

代码如下:
require_once 'sqlTools.class.php';//封装类,可执行dql、dml语句
$info=$_POST['info'];
$sql="select name,password,email from user_500 where name like '%$info%' or password like '%$info%' or email like '%$info%'";
$sqlTools=new SqlTools();
$res=$sqlTools->execute_dql($sql);
while ($row=mysql_fetch_assoc($res)){
$row['name']=preg_replace("/($info)/i","\\1",$row['name']);
$row['password']=preg_replace("/($info)/i","\\1",$row['password']);
$row['email']=preg_replace("/($info)/i","\\1",$row['email']);
echo $row['name']."-->".$row['password']."-->".$row['email']."
";
}
?>

思路分析:
将sql语句中包含的%$info%交给DBMS执行的时候,他会查找字段中含有变量$info的值的信息,
%$info--->查找以$info的值结束的信息
$info%--->查找以$info的值开头的信息
通过正则函数preg_replace()将搜索到的关键字高亮显示,比如,
    $row['name']=preg_replace("/($info)/i","\\1",$row['name']);
    的意思是:通过POST方接收到的值$info替换为加上样式(红色加粗)的结果,并将结果重新赋给$row[‘name']
如果要搜索多个关键字的话,可以对接收到值$info进行分割,比如$info_more=explode(" ",$info);//这种方式能对以空格隔开的关键字进行分割,再对分割后的结果挨个进行查询,同样,可以使用正则表达式函数进行替换工作,以高亮显示关键字
sqlTools.class.php的源代码:
代码如下:
class SqlTools{
private $host="localhost";
private $dbname="test";
private $dbuser="root";
private $dbpwd="";
private $conn;
public function __construct(){
$this->conn=mysql_connect($this->host,$this->dbuser,$this->dbpwd);
if(!$this->conn){
die("连接数据库失败".mysql_error());
}
mysql_select_db($this->dbname,$this->conn) or die("找不到该数据库".mysql_error());
mysql_query("set names utf8");
}
public function execute_dml($sql){
$bool=mysql_query($sql);
if ($bool){
if ($bool>0) {
return 1;
}else{
return 2;
}
}else {
return 0;
}
}
public function execute_dql($sql){
$res=mysql_query($sql);
return $res;
}
public function close_conn(){
mysql_close($this->conn);
}
}
?>

原创文章:WEB开发_小飞
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template