今天要做个搜索功能(即在数据库中找出含有搜索关键字的所有记录来),在网上找到了这么段代码,改造用了下感觉很好。轻松就把搜索问题解决了.
感谢那位英雄,也希望对大家有帮助~
div class="relatedLinks">
<h3>相关内容</h3>
<!--#include file="inc/connect.asp" -->
<%
searchdata=discribe '从文本框中获得输入的关键字
if trim(searchdata)="" then '如果没有关键字的输入或者只输入的空格,警告!
response.write "没有相关内容"
response.end
end if
searchdata=replace(searchdata,"‘","’")'将获得的字符串中英文单引号换成中文单引号
searchdata=Rtrim(LTrim(searchdata) )'去掉获得的字符串最左边空格和最右边空格
sql1="" '网站关键字匹配sql语句
sql2="" '网站标题匹配sql语句
searchdatatmp=split(searchdata,"|") '将输入的字符串根据空格分开,获得一个数组
max=ubound(searchdatatmp) '得出这个数组的维数,即输入的关键字个数
if max=0 then '如果max等于0说明只输入了一个关键字,那么就不需要循环处理
sql1=sql1&" title like '%" & searchdatatmp(i) & "%' " '网站关键字模糊搜索
sql2=sql2&" discribe like '%" & searchdatatmp(i) & "%' " '网站标题模糊搜索
else '如果含有多个关键字,采用循环处理sql语句
for i=0 to max '如果关键字很多,我们要求每一个搜索都要匹配每一个关键字,通过循环来实现
if i=0 then '写入下面sql语句作为开头,仔细研究一下下面的代码
sql1=sql1&" (title like '%" & searchdatatmp(i) & "%' or "
sql2=sql2&" (discribe like '%" & searchdatatmp(i) & "%' or "
else
if i=max then '如果循环到最后一个关键字,写入下面sql语句作为结尾
sql1=sql1&" title like '%" & searchdatatmp(i) & "%') "
sql2=sql2&" discribe like '%" & searchdatatmp(i) & "%') "
else '如果关键自己不是开头的也不是结尾的,那么循坏写入下面的sql语句
sql1=sql1&" title like '%" & searchdatatmp(i) & "%' and "
sql2=sql2&" discribe like '%" & searchdatatmp(i) & "%' and "
end if
end if
next '循环结束
end if
sql="select * from news where "&sql1&" or "&sql2&" and checked=true and deleted<>true order by id desc"
Set rs=Server.CreateObject("Adodb.Recordset")
rs.open sql,conn,1,3
totalnumber=rs.recordcount
%>
<% for i=1 to 5
if rs.bof or rs.eof then
if i =1 then response.write("没有相关内容")
exit for
end if%>
<% gettime=left(rs("time"),11)
cstr(gettime)
do while right(gettime,1)<>" "
gettime=left(gettime,len(gettime)-1)
loop
gettime=replace(gettime,"-","/")
if right(gettime,1)=" " then gettime=left(gettime,len(gettime)-1)%>
<div id="recentnewstitle"><a href="shownews.asp?id=<%=rs("id")%>&sort=news#info" title=’点击查看文章<%=chr(13)&"文章标题:"%><%=rs("title")&chr(13)&"文章作者:"%><%=rs("auther")&chr(13)&"文章来源:"%><%=rs("root")&chr(13)&"更新时间:"&gettime&chr(13)&".:::我的网站:::."%>’>
<%=rs("title")%>
</a></div>
<% rs.movenext
next
if totalnumber>5 then%>
<a href=#info onclick="return toggle_collapse('allrelated')"><font color=#cccccc>显示/隐藏全部内容</font></a>
<div id="allrelated" style="display:none">
<% for i=6 to totalnumber
if rs.bof or rs.eof then
exit for
end if%>
<% gettime=left(rs("time"),11)
cstr(gettime)
do while right(gettime,1)<>" "
gettime=left(gettime,len(gettime)-1)
loop
gettime=replace(gettime,"-","/")
if right(gettime,1)=" " then gettime=left(gettime,len(gettime)-1)%>
<div id="recentnewstitle"><a href="shownews.asp?id=<%=rs("id")%>&sort=news#info" title='点击查看文章<%=chr(13)&"文章标题:"%><%=rs("title")&chr(13)&"文章作者:"%><%=rs("auther")&chr(13)&"文章来源:"%><%=rs("root")&chr(13)&"更新时间:"&gettime&chr(13)&".:::我的网站:::."%>’>
<%=rs("title")%>
</a></div>
<% rs.movenext
next
%></div>
<%end if
rs.close
set rs=nothing
%>
</div>