Website Search Engine

So when would you need a search engine on your website?  Well, one example would be if you had an FAQ (Frequently Asked Questions) database.

You could simply list all of your FAQ’s on one web page, but if you have a lot of them it would be a good idea to put them in a database table and let your website users search them by keyword or key phrase.

To do this, create a database called MyData and a table called tblFAQ with these fields:
ID – autonumber
Question – text field
Answer – text field
DateEntered – date/time field

Then, start adding some questions and answers to your database.

Next, create a page called /SearchEngine.asp and copy the below code into your page:

<!--#INCLUDE VIRTUAL="/includes/connection.asp" -->

<form name="search" method="post" action="searchresults.asp">
Search our FAQ's<br>
<input type="text" name="searchterm">
<input type="submit" name="Submit" value="Search">
</form>

<%
DIM strSearchterm
strSearchterm = Request.Form("searchterm")

IF strSearchterm <> "" THEN
DIM mySQL, objRS
mySQL = "SELECT * FROM tblFAQ WHERE (Question LIKE '%" & strSearchterm & "%') " & _
"OR (Answer LIKE '%" & strSearchterm & "%')"
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open mySQL, objConn, adOpenKeyset, adLockPessimistic, adCmdText

     IF objRS.EOF THEN
     Response.Write "Sorry, no results were found."
     ELSE
%>

     <div align="center">Search Results</div>
     <% DO WHILE NOT objRS.EOF %>
     <p><strong><%=objRS("Question")%></strong><br>
     <%=objRS("Answer")%></p>
<%
     objRS.MoveNext
     Loop
     END IF

ELSE
' No search term was submitted.
Response.Write "Sorry, no results were found."
END IF
%>

This script will display your search form each time the page is accessed.  When a search term is submitted, it will search both the question and answer fields in your database for any data that contains the search term.  There you have it, a simple search engine.

< Back to ASP Scripts