Writing Your First ASP Application ( Quick Start ) - Simplifying The Code
(Page 6 of 8 )
The ASP page for showing the users is functional as shown in the previous section. But it can be pretty difficult to modify the look and feel of the page when you have a hearty mix of script and HTML. And what if you want to show the users on more than one page? Do you want to type the same code over and over again?
One method of simplifying your ASP pages is to use include files and functions. Include files are other basically other files containing HTML and/or script that you can reference from your ASP page, and will be considered part of the ASP page when the page is rendered. In this method, you can put code that you want to use on more than one page in an include file, and reference the file from many ASP pages. Include files can also be used to hide complex code to make it easier to modify the design of the HTML on your web pages.
Here is another copy of the showusers.asp page, this one using an include file with a function to show the users:
<%@ LANGUAGE="VBSCRIPT" %><!-- #INCLUDE FILE='functions.inc' -->Users currently on the website:
<HR>
<%
ShowUsers
%>
And here is the functions.inc:
<%
Sub ShowUsers()
dim conn
dim strsql
dim mycount
‘ Create a SQL statement to insert the name into our table
strsql = "select UserName from UsersOnline”
‘ Open the database using our DSN
strconn = “DSN=UserBase”
set conn = server.createobject("adodb.connection")
conn.open strconn
‘ Open the recordset containing user names
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strsql, conn, 3,3
‘ Set the mycount variable to contain the number of users in the database
mycount=rs.recordcount
if mycount < 1 then
‘ There were no users logged in
response.write “None”
else
for a = 1 to mycount
‘ Write out the user names
response.write(rs(“UserName”))
if a < mycount then
rs.movenext
end if
next a
endif
‘ Close the recordset
rs.close
set rs = nothing
‘ Close the database connection
conn.close
set conn = nothing
End Sub
%>
As you can see, all of the working code has been put inside the functions.inc file in a subroutine called “ShowUsers”. The ASP page has become very compact and easy to read and modify. In addition, the functions.inc file can be included on any ASP page in your application, and used to display the users wherever you would like.
Next: Removing Users From The List >>
More ASP Articles
More By Rich Smith