php关键词查询的实现方法:首先获得用户输入;然后分解用户输入的多个关键词,并存入数组中;接着根据多个关键词构建sql语句;最后对搜索结果排序,并显示当前搜索结果即可。
推荐:《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]%''";}$query_rs .= ") t order by last_access desc"; //对搜索结果排序//执行sql语句$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>当前关键词:<?phpfor($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 关键词查询的实现方法的详细内容。