<script>ec(2);</script>
PHP对于数据库的搜索主要通过使用SQL语句中的like子句来实现。如果同时搜索多个关键词,可以使用union子句来将搜索结果合并起来。以下代码实现了一个搜索页面。
$colname_rs = $_GET[''key'']; //获得用户输入
$result = explode('','',$_GET[''key'']);//分解用户输入的多个关键词,存入$result数组
mysql_select_db($database_conn, $conn); //连接数据库
//根据多个关键词构建SQL语句
$query_rs = "SELECT * FROM (";
for($i=0;$i
{
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);
 
Statement: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