您好,欢迎访问一九零五行业门户网

PHP如何实现多个关键词查询?

php实现多个关键词查询的方法:1、使用sql语句中的like子句对数据库的搜索;2、同时搜索多个关键词,使用union子句来将搜索结果合并起来即可。
php实现多个关键词查询的方法:
php对于数据库的搜索主要通过使用sql语句中的like子句来实现。如果同时搜索多个关键词,可以使用union子句来将搜索结果合并起来。以下代码实现了一个搜索页面。
引用
<?php require_once(''connections/conn.php''); ?><?php$colname_rs = $_get[''key'']; //获得用户输入$result = explode('','',$_get[''key'']);//分解用户输入的多个关键词,存入$result数组mysql_select_db($database_conn, $conn); //连接数据库
根据多个关键词构建sql语句
$query_rs = "select * from (";for($i=0;$i<count($result);$i++) //根据每个搜索关键词构建sql语句{if($i==0) //对第一个关键词,不使用union$query_rs .= "select * from searchtable where title like ''%$result[0]%''or content like ''%$result[0]%''";else //对其他关键词,使用union连接$query_rs .= " union select * from searchtable where title like''%$result[$i]%'' or content like ''%$result[$i]%''";}
对搜索结果排序执行sql语句
$query_rs .= ") t order by last_access desc";$rs = mysql_query($query_rs, $conn) or die(mysql_error());$row_rs = mysql_fetch_assoc($rs);$totalrows_rs = mysql_num_rows($rs);?><html><head><title>search</title><meta http-equiv="content-type" content="text/html; charset=gb2312"></head><body><form name="form1" method="get" action="?"><div align="center">请输入要搜索关键词:<input name="key" type="text" size="64" value="<?php echo $_get[''key''] ?>"><input type="submit" value="submit"></div></form><p align="center"><b>当前关键词:<?php
循环显示关键词
for($i=0;$i<count($result);$i++) { echo $result[$i]." ";}?></b></p><p><hr></p><?php if($totalrows_rs>0) do { //显示当前搜索结果 ?><p>* <a href="show.php?key=<?php echo $colname_rs ?>&id=<?php echo$row_rs[''id'']; ?>"><?php echo $row_rs[''title'']; ?></a>(<?php echo$row_rs[''click'']; ?> | <?php echo $row_rs[''last_access'']; ?>)</p><?php } while ($row_rs = mysql_fetch_assoc($rs)); ?></body></html><?phpmysql_free_result($rs);?>
相关学习推荐:php编程从入门到精通
以上就是php如何实现多个关键词查询?的详细内容。
其它类似信息

推荐信息