本文实例讲述了PHP实现关键字搜索后描红功能。分享给大家供大家参考,具体如下:
在刚开始学习php的时候,就对搜索过后的关键字描红感到好奇,但是这几天在巩固php基础的时候,就发现原来这样的效果实现并不难。按照惯例,首先给大家看看效果图吧。
运行效果图
数据库相关
代码
<!DOCTYPE html
<html
<head
<meta charset="utf-8"
<meta http-equiv="X-UA-Compatible" content="IE=edge"
<title </title
<link rel="stylesheet" href=""
</head
<body
<form action="14.php" method="post"
请输入关键字:<input type="text" name="keyword"
<input type="submit" value="提交" /
</form
<?php
if(!empty($_POST['keyword'])){
$keyword = $_POST['keyword'];//获取输入的关键字
//进行数据库连接
$conn = mysql_connect("localhost","root","1234");
if(!$conn){
die("数据库连接失败");
}
$flag = mysql_select_db("book",$conn);
if(!$flag){
die("数据库打开失败");
}
mysql_query("set names utf8");
$sql = "select * from book where name like '%$keyword%' or description like '%$keyword%'";
$result = mysql_query($sql,$conn);
while($row = mysql_fetch_assoc($result)){
?
<div style="width:300px;height:100px;background-color: #ccc;margin-bottom: 10px"
<p 书名:<?php echo str_ireplace($keyword, "<font color='#f00' $keyword</font ",$row['name'])? </p
<p 描述:<?php echo str_ireplace($keyword, "<font color='#f00' $keyword</font ",$row['description'])? </p
</div
<?php
}
}else{
echo "很遗憾,没有找到书籍";
}
?
</body
</html
最后说一下实现的原理,首先先获取从文本框输入的关键字文字,然后就是连接数据库进行查询,将书名中或者描述中包含关键字文字的记录查询出来,把查询到的结果循环显示出来,在显示书名和描述的时候,用str_ireplace()
函数将其中的关键字文字替换成带有红色的文字,就实现了关键字描红的效果。