Suppose that you want to publish the contents of a database on the Web. With ASP, you can use ADO objects in your VBScript code to access databases. As discussed in Chapter 28, "Using ActiveX Data Objects (ADO)," to access a database, you first need to identify a data source. The actual database can be located on the Web server itself or on another machine, as long as you can connect to it via a data source.
When setting up data sources for use with ASP, you generally should use a System Data Source Name (DSN) rather than a User DSN. The System DSN allows the data source to be available to the Web server at all times, not just when a certain user is logged in.
See "Setting Up a Data Source," p. 613.
You can also use a DSN-less connection that does not require you to set up a data source. This is also discussed in Chapter 28.
In this section, the examples assume that the BIBLIO data source has been set up, as described in Chapter 26, "Using Data Access Objects (DAO)."
See "Setting Up a DAO Project," p. 567.
If you have problems connecting to a Microsoft SQL Server data source using standard security on a different machine from the Web server, you might receive an error such as Connection Open error in the function CreateFile(). This means that the NT account making the connection (usually the I_USR account) does not have sufficient authority on the NT SQL server.
Querying a Database
With what you have read up to this point, you have all of the knowledge necessary to run an ADO database query and display the results in a Web page. However, even a small database such as BIBLIO.MDB has many records. Therefore, you need to provide some way to query the database for just the records that the user wants to see, which of course means you need to accept user input.
Setting Up a Sample Query Page
The <FORM> tag, built in to the HTML language, allows user input to be sent to the Web server. Let's set up an HTML form, DBQUERY.HTM, that allows the user to enter an author's name to search for. Simply enter the HTML code in Listing 31.3 and save it on the Web server.
Listing 31.3 DBQUERY.HTM is a Standard HTML Form
<HTML><BODY> <H1>Biblio Database Search</H1><HR> <FORM ACTION=dbsearch.asp METHOD=POST> Enter Author to search for: <INPUT TYPE=TEXT NAME=txtSearch> <INPUT TYPE=SUBMIT VALUE="Begin Search"> </FORM> </BODY></HTML>
An HTML form consists of different types of <INPUT> tags, which appear in the user's browser as data entry fields. The contents of these fields are sent to the Web server when the user "submits" a form.
Note that the code in Listing 31.3 is not an ASP page. It contains no VBScript statements and has the standard .HTM extension. It simply submits an HTML form to an ASP page called DBSEARCH.ASP. The purpose of DBSEARCH.ASP, shown in Listing 31.4, is to perform the actual search.
Writing DBSEARCH.ASP is fairly easy, as well. You basically have three things to do:
Retrieve the value the user wants to search for from the form field txtSearch, and use it to build a query.
Execute the query using ADO to obtain a recordset.
Send the contents of the recordset back to the user's browser.
The code for DBSEARCH.ASP, shown in Listing 31.4, uses the Like statement in the SQL query.
Listing 31.4 DBSEARCH.ASP Performs the Database Search
<HTML><BODY> <% Dim cn Dim rs Dim sSQL Dim sSearchString 'GET THE SEARCH STRING FROM THE FORM sSearchString = Request.Form("txtSearch") If sSearchString = "" Then Response.Write ("No search string entered!") Response.End End If 'CONNECT TO THE DATABASE AND PERFORM THE SEARCH Set cn = Server.CreateObject("ADODB.Connection") cn.Open "DSN=BIBLIO" sSQL = "SELECT * FROM AUTHORS WHERE AUTHOR LIKE " sSQL = sSQL & "'" & sSearchString & "%' ORDER BY AUTHOR" Set rs = cn.Execute(sSQL) %> <TABLE BORDER=1> <TR>Author's Name</TR> <% 'DISPLAY THE RESULTS IN A TABLE While Not rs.EOF Response.Write ("<TR><TD>") Response.Write rs.Fields("Author") Response.Write ("<TD></TR>") rs.MoveNext Wend rs.Close cn.Close Set rs = Nothing Set cn = Nothing %> </TABLE> </BODY></HTML>
After you have created DBQUERY.HTM and DBSEARCH.ASP, you should be able to open the URL for DBQUERY.HTM, enter a few letters of the alphabet, and have the matching records displayed in the browser (see Figures 31.4 and 31.5).
This page contains a standard HTML form that allows the user to enter a value and post it to an ASP page for processing.
VBScript code on the server returns the contents of a recordset in the form of an HTML table.
In your database search example, you used separate ASP and HTM files. You could have just as easily combined the two files into a single ASP file. The only change you would need to make would be to have the form action refer to the same page. You might also want to use an if statement to check for the form value to see if you need to display the results:
<% If Request.Form("txtSearch") <> "" Then DisplayResults %>
The preceding line of code assumes that you have written a custom function, DisplayResults, to execute the query.
Displaying Data with Drill-Down Links
The code in Listings 31.3 and 31.4 uses an HTML form field to retrieve the search criteria from the user. The user must first type a value into a text box and press a button. However, many times it is more convenient to use hyperlinks to perform database navigation. For example, suppose that you want to allow the user to click an author's name in the list of authors to display the books by that author. You can do this very easily by generating hyperlinks for each author. To generate these hyperlinks, modify the While loop code from Listing 31.4 as follows:
'DISPLAY THE RESULTS IN A TABLE While Not rs.EOF Response.Write ("<TR><TD><A HREF=author.asp?id=") Response.Write rs.fields("AU_ID") & ">" Response.Write rs.Fields("Author") Response.Write ("</A><TD></TR>") rs.MoveNext Wend
Run a search, and each author's name in the resulting list should appear as a hyperlink to a new ASP file, AUTHOR.ASP. If you choose View Source in your browser, you will see that each hyperlink is unique:
<A HREF=author.asp?id=16061>Jackson, Bruce</A>
The preceding line of HTML passes a parameter id to the ASP page AUTHOR.ASP. If you click the hyperlink, the browser will ask the server for this URL:
Note that the URL includes the id parameter, which is separated from the base (or target) URL by a question mark. If there were additional parameters, they would be separated by an ampersand (&). The syntax for using parameters in a URL is as follows:
http://targetURL ? parm1name=parm1value & parm2name=parm2value & parm3name=parm3value etc...
The collection of parameters in an URL is also known as the query string, and can be retrieved with the QueryString collection of the Request object:
If Request.QueryString("id") = "" Then Response.Write "No ID entered!"
As with the Request.Form example in Listing 31.4, the value passed to an ASP page in the query string can be retrieved and used in a database query:
sSQL = "SELECT Title FROM [Title Author], [Titles] " sSQL = sSQL & " WHERE [Title Author].ISBN = [Titles].ISBN " sSQL = sSQL & " and [Title Author].AU_ID=" & Request.QueryString("id")
As an exercise, create AUTHOR.ASP using the preceding query. Except for the database field names, the structure of the ASP file should be identical to that in Listing 31.4.
Updating Information in a Database
Although displaying data with ASP is useful, at some point you also need to add or edit information. The previous section described two ways to get input from a client's browser to an ASP page:
Posting with HTML forms
Adding parameters to the URL querystring
Both of these methods are useful and appropriate in certain cases, but using the POST method with HTML forms is much more versatile. In the examples shown so far, you have used only the TEXT input field. However, there are many types of HTML form elements that can be used, such as radio buttons, drop-down boxes, and free-form text areas. One type of field that is very useful when dealing with database updates is a hidden form field. A hidden form field is like a text field, but the user cannot see it or change its value. This type of field can be generated from an ASP page and sent down to the browser. When the user submits a form, the value of a hidden form field is sent back to the server with the other form fields.
Revisit the example in Listings 31.3 and 31.4, and add edit capability for the author's name and birth year. In addition, you will consolidate all of the functionality from the previous example into subroutines in a single ASP page:
AskForAuthors takes the place of DBQUERY.HTM.
GetAuthorList replaces DBSEARCH.ASP.
DisplayEditScreen, a new procedure, displays a form that allows you to edit an author's information.
UpdateDBInfo changes the database.
The code for the new ASP page, AUTHOREDIT.ASP, is shown in Listing 31.5.
Listing 31.5 ASP Page Allowing Searching and Editing
<HTML><BODY> <% Dim cn Dim rs Dim sSQL Const MYASPNAME="authoredit.asp" Sub AskForAuthors() Response.Write ("<H1>Biblio Database Search</H1><HR>") Response.Write ("<FORM ACTION=" & MYASPNAME & "?mode=search METHOD=POST>") Response.Write ("Enter Author to search for:") Response.Write ("<INPUT TYPE=TEXT NAME=txtSearch>") Response.Write ("<INPUT TYPE=SUBMIT VALUE=""Click to Search"">") Response.Write ("</FORM>") End Sub Sub GetAuthorList() 'CONNECT TO THE DATABASE AND PERFORM THE SEARCH Set cn = Server.CreateObject("ADODB.Connection") cn.Open "DSN=BIBLIO" sSQL = "SELECT * FROM AUTHORS WHERE AUTHOR LIKE " sSQL = sSQL & "'" & Request.Form("txtSearch") sSQL = sSQL & "%' ORDER BY AUTHOR" Set rs = cn.Execute(sSQL) 'DISPLAY THE RESULTS IN A TABLE Response.Write("<TABLE BORDER=1><TR>Author's Name</TR>") While Not rs.EOF Response.Write ("<TR><TD><A HREF=" & MYASPNAME & "?id=") Response.Write rs.fields("AU_ID") & "&mode=dispedit>" Response.Write rs.Fields("Author") Response.Write ("</A><TD></TR>") rs.MoveNext Wend rs.Close cn.Close End Sub Sub DisplayEditScreen() 'CONNECT TO THE DATABASE AND GET THIS AUTHOR'S INFO Set cn = Server.CreateObject("ADODB.Connection") cn.Open "DSN=BIBLIO" sSQL = "SELECT * FROM AUTHORS WHERE AU_ID= " & Request.QueryString("id") Set rs = cn.Execute(sSQL) 'GENERATE THE HTML FORM Response.Write ("<H1>Edit Author Information</H1><HR>") Response.Write ("<FORM ACTION=" & MYASPNAME & "?mode=updatedata METHOD=POST>") Response.Write ("Name:<INPUT TYPE=TEXT NAME=txtName") Response.Write (" VALUE='" & rs.Fields("Author") & "'><BR>") Response.Write ("Year Born:<INPUT TYPE=TEXT NAME=txtYear") Response.Write (" VALUE='" & rs.Fields("Year Born") & "'><BR>") Response.Write ("<INPUT TYPE=HIDDEN NAME=AuthorID VALUE=") Response.Write (rs.Fields("AU_ID") & ">") Response.Write ("<INPUT TYPE=SUBMIT VALUE=""Update Info"">") Response.Write ("</FORM>") End Sub Sub UpdateDBInfo() 'CONNECT TO THE DATABASE Set cn = Server.CreateObject("ADODB.Connection") cn.Open "DSN=BIBLIO" 'BUILD SQL UPDATE STATEMENT sSQL = "UPDATE AUTHORS SET Author='" & Request.Form("txtName") & "'," sSQL = sSQL & "[Year Born]=" & Request.Form("txtYear") sSQL = sSQL & " WHERE AU_ID=" & Request.Form("AuthorID") cn.Execute(sSQL) 'DISPLAY A MESSAGE Response.Write ("<H1> Information Updated!</H1>") AskForAuthors End Sub Select Case Request.QueryString("mode") Case "search" GetAuthorList Case "dispedit" DisplayEditScreen Case "updatedata" UpdateDBInfo Case Else AskForAuthors End Select Set rs = Nothing Set cn = Nothing %> </TABLE> </BODY></HTML>
When working with user input, be wary of the quote character. You might need to write a function to manipulate quotes in a form field before using the field value in an SQL statement.
Listing 31.5 is a single ASP file, yet it generates four distinct HTML screens. The query string parameter mode determines what action the ASP page performs.