Sie sind auf Seite 1von 142

http://www.learnasp.com/learn/dbtablelists.

asp Página 1 de 142

HTML List Box from Column


This page demonstrates the capabilities how to display a list box from a SQL statement. This is the
simplest possible example. The script to display a list from a database is:
<html><head>
<TITLE>dblist.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<%
myDSN="DSN=Student;uid=student;pwd=magic"
mySQL="select author from authors where AU_ID<100"
' displays a database field as a listbox
set conntemp=server.createobject("adodb.connection")
conntemp.open myDSN
set rstemp=conntemp.execute(mySQL)
if rstemp.eof then
response.write "no data for<br>"
response.write mySQL
conntemp.close
set conntemp=nothing
response.end
end if
%>
<form action="dblistrespond.asp" method="post">
<Select name="authorname">
<%
' Now lets grab all the data
do until rstemp.eof %>
<option> <%=RStemp(0)%> </option>
<%
rstemp.movenext
loop
rstemp.close
set rstemp=nothing
conntemp.close
set conntemp=nothing
%>
<input type="submit" value="Choose Author">
</Select></form>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 2 de 142
</body></html>
The form responder dblistrespond.asp is:
<html><head>
<TITLE>dblistrespond.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<%
my_author=request.form("authorname")
%>
You choose <%=my_author%><br>Thanks!<br>
</body></html>

Subroutines Query2List by Charles Carroll


Subroutines can save you having to repeat blocks of code and can optionally be placed in separate files
and included when needed, thus making your pages not appear to have lots of code in-line.

<html><head>
<TITLE>subdblist.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<form>
<%
theDSN="DSN=student;uid=student;pwd=magic"
call query2list("select distinct city from publishers","cy",theDSN)
call query2list("select distinct state from publishers","st",theDSN)
call query2list("select distinct zip from publishers","zp",theDSN)
%>
</form>
<!--#include virtual="/learn/test/subdblist.inc"-->
</body></html>

The include file lib_dblist.asp looks like:

<%sub query2list(myquery,myname,myDSN)
dim conntemp, rstemp
set conntemp=server.createobject("adodb.connection")
conntemp.open myDSN
set rstemp=conntemp.execute(myquery)
%>
<Select name="<%=myname%>">

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 3 de 142
<%
do while not rstemp.eof
thisfield=trim(RStemp(0))
if isnull(thisfield) or thisfield="" then
' ignore
else
response.write "<option>" & thisfield & "</option>"
end if
rstemp.movenext
loop
%>
</select>
<%rstemp.close
set rstemp=nothing
conntemp.close
set conntemp=nothing
end sub%>

Subroutines Db2list "Best" Approach by Charles Carroll


Subroutines could be considerably more useful if they took optional parameters. Since they don't we can
jury rig a system whereby a subroutine is invoked with two parameters: a delimiter and a string. And the
string itself contains the various parameters. This approach implements a more optional parameter "like"
solution.

<html><head>
<TITLE>subdblistbest.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<form>
<%call db2list("^","select distinct city from publishers^city^New York")%>
<%call db2list("^","select distinct state from
publishers^state^NY^table^DSN=student;uid=student;pwd=magic")%>
<%call db2list("^","select distinct zip from publishers^Zip Code^^table")%>
</form>
<!--#include virtual="/learn/test/lib_dblistbest.asp"-->

The include file lib_dblistbest.asp looks like:

<%
sub db2list(mydelim,myparm)

dim myparameters
myparameters=SPLIT(myparm,mydelim)
parmcount=ubound(myparameters)
myquery=myparameters(0)
label=myparameters(1)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 4 de 142
default=myparameters(2)
if parmcount>2 then
format=lcase(myparameters(3))
end if
if parmcount>3 then
connstring=myparameters(4)
else
connstring="DSN=Student;uid=student;pwd=magic"
end if

set conntemp=server.createobject("adodb.connection")
conntemp.open connstring
set rstemp=conntemp.execute(myquery)
If format="table" then%>
<table width="100%" border="0" cellspacing="1"><td>
<%end if
response.write label
If format="table" then%>
</td><td>
<%end if%>
<Select>
<option value="<%=default%>" selected><%=default%></option>
<%
do while not rstemp.eof %>
<option><%=RStemp(0)%></option>
<%
rstemp.movenext
loop
conntemp.close
%>
</select>
<%If format="table" then%>
</td><tr></table>
<%end if
end sub%>

Custom Security/Authentication #1
You can limit access to specific pages in your website using several methods documented at
http://www.activeserverpages.com/learn/authenticate.asp Here we will demonstrate how to use custom
authentication and also cover session and application issues. You can try our authentication example by:

 Attempt to access test/securitytestlevel1.asp or test/securitytestlevel2.asp or


test/securitylevel3required.asp

 All attempts to read those pages should fail.

 Now if you login at test/securitylogin.asp. Sample logins that will work because of the database
data are:

 user=chaz, password=chaz, securitylevel=1

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 5 de 142
 user=chaz2, password=chaz2, securitylevel=2

 user=chaz3, password=chaz3, securitylevel=3

 You can also try logging out at test/securitylogout.asp which will put you back to square one. No
security level will exist then.

The next page details the source code for all scripts needed to implement our example but here is the list:
the login screen where someone can enter username/password and
securitylogin.asp
confirm security level. It is a form that submits to
securityloginrespond.asp
securityloginrespond.asp
the screen to abandon someone's username/password and security
securitylogout.asp
level
securitylevel1required.asp which can be included on individual pages to limit access to people with
securitylevel2required.asp that security level, i.e/:
securitylevel3required.asp <!--#include file="securitylevel1required.asp"-->
securitytestlevel1.asp
which demonstrate how security is implemented. These scripts cannot
securitytestlevel2.asp
be seen unless you login.
securitytestlevel3.asp
which anyone attempting to access a page without appropriate security
securitynotallowed.asp
level is redirected to.
a 3 column Access database: username, password, security level.
Sample data is:
user=chaz, password=chaz, securitylevel=1
/learn/test/customsecurity.mdb user=chaz2, password=chaz2, securitylevel=2
user=chaz3, password=chaz3, securitylevel=3
Download Database
In a production application, this database would be located
OUTSIDE of the web structure (and accessed by DSN) so it could
never be downloaded by a user.

Custom Security/Authentication #2
To implement custom security via a database, we use the following scripts that we will present the source
code for:

Here is the securitylogin.asp script:

Test the Script --> /learn/test/securitylogin.asp

<html><head>

<title>securitylogin.asp</title>

</head><body bgcolor="#FFFFFF">

<form action="securityloginrespond.asp" method="POST">

Sign In Page:<p>

Name -&gt; <input NAME="userName" size="20"><br>

Password -&gt; <input NAME="userPassword" size="20"><br>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 6 de 142
<input type="submit"><input type="reset">

</form></body></html>

Here is the securityloginrespond.asp script:

<html><head>

<TITLE>securityloginrespond.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<%

dbname="/learn/test/secret/customsecurity.mdb"

myname=request.form("username")

mypassword=request.form("userpassword")

set conntemp=server.createobject("adodb.connection")

cnpath="DBQ=" & server.mappath(dbname)

conntemp.Open "DRIVER={Microsoft Access Driver (*.mdb)}; " & cnpath

sqltemp="select * from users where user='"

sqltemp=sqltemp & myname & "'"

set rstemp=conntemp.execute(SQLTemp)

If rstemp.eof then%>

we don't have a user named <%=Myname%> on file!<br>

Try <A href='securitylogin.asp'>Logging in</a> again

<%response.end

end if

If rstemp("Password")=mypassword then

session("name")=rstemp("user")

session("securitylevel")=rstemp("securitylevel")

response.write "Security Level=" & session("securitylevel")

else%>

Password Unrecognized<br>

Try <A href='securitylogin.asp'>Logging in</a> again

<%response.end

end if

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 7 de 142
rstemp.close

conntemp.close

set rstemp=nothing

set conntemp=nothing

%>

</body></html>

Here is the securitylogout.asp script:

Test the Script --> /learn/test/securitylogout.asp

<html><head>

<title>securitylogout.asp</title>&

<body>

<%

session.abandon

%>

Logged out Now!!!

</body>

</html>

Here is the securitylevel1required.asp script:

Test the Script --> /learn/test/securitylevel1required.asp

<%

response.expires=0

if session("securitylevel")>0 then

' nothing to do

else

response.redirect "securityunauthorized.asp"

end if

%>

Here is the securityunauthorized.asp script:

Test the Script --> /learn/test/securityunauthorized.asp

<html><head>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 8 de 142
<title>unauthorized</title>&

<body>

You are unauthorized to read that page!

</body></html>

Here is the securitytestlevel1.asp script:

Test the Script --> /learn/test/securitytestlevel1.asp

<!--#include file="securitylevel1required.asp"-->

<html><head>

<title>New Page </title>

<META HTTP-EQUIV="Expires" CONTENT="Tue, 04 Dec 1993 21:29:02 GMT">

</head><body>

My level 1 secret is Pretty Hot!!!<br>

Our president may not be as honest as we believed!

</body>

</html>

Authentication -- 3rd Party Method


written and ©1998, 99 by Kevin Flick www.flicks.com creator of Authentix
You won't want to use a third party Basic Authentication filter if
 protecting your premium content directories does not warrant the price of registration.

 Basic Authentication is not secure enough for your purposes

 you want all accounts of every type in one userbase, specifically the NT user account database, for
administrative reasons.

Authentix, a third party Basic Authentication filter is the way to go if


 You want the high performance that a filter offers

 You want to be able to add and modify users from ASP and don't want the ASP pages to have SysAdmin
priviledges

 You want browser independence

 You don't want any chance of compromising NT username/password security

 You want to separate your web-users from your NT Accounts

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 9 de 142
 You are concerned about performance. In addition to the speed associated with filter based solutions,
AuthentiX is unique in that it does not impersonate an NT account to grant access, eliminating the CPU-
expensive call to LogonUser on every request.

 You have directories you want to validate against an ODBC database

 You want to authenticate multiple IIS servers against a single ODBC machine on the LAN.

 You want to use browser based remote administration

 you need to protect all content in a directory: htm, asp, gif, jpg, zip, and so on.

 you want advanced features like

o limiting concurrent logins,

o bandwith, request and login throttling,

o protect by IP, Domain Name and by referrer

AuthentiX is a fast, filter based third party tool for IIS authentication developed by Flicks
Software (me).
It allows you to protect content directories and individual files by asking for usernames and
passwords held separately from the Windows NT usernames and passwords, ensuring the the
security of your NT accounts.
Definitions
 ODBC = Open Database Connectivity.

How to set up AuthentiX, a third party Basic Authentication filter


Setting up AuthentiX is easy and straighforward.
Download the free evaluation version, unzip it and run setup.exe. Installshield will guide you
through the rest of the installation process.
 Make sure Basic (Clear Text) is off and Allow Anonymous is on. You can leave Windows NT Challenge
Response on or off.

 Create a user. From the main AuthentiX dialog, click the Users button, then Add. Type a username and
password and click OK. The user will be added to the User List. Click OK.

 Create a group. From the main AuthentiX dialog, click the Groups button, then Add. Type a Groupname,
click on a user (to highlight it) listed in the Non-Members list box, and click Add. The user will be moved
to the Members list box. Click OK. You should now see the group in the group list. Click OK.

 Protect a directory. From the main AuthentiX dialog, click the Access button, then Add. Click the Browse
button and select a directory that is part of your web directories, and that you would like to protect. Click
the By Group button and add the group you created in the previous step. Click OK. You should now see
that the group is protecting that directory. Verify that the group is protecting the desired directory and click
OK twice

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 10 de 142
 Using a browser, go to the URL that the directory is accessed from using IIS. It should prompt you for your
username and password.

 Type the username and password and you should be granted access.

You can see how to set up ODBC and other advanced options by downloading the online
Windows help file or checking out the online Guided Tour. Because the pace of enhancements
and improvements to this product sometimes outstrips the documentation, you can find out more
by working with the free evaluation download.

String Functions by Charles Carroll


String functions are very useful for parsing data from ASCII files, formatting output in complex ways and
parsing form input. The following scripts provides a sample of some crucial VBScript string functions in
action. The string functions demonstrated are:

Instr(string,searchstring)

returns a numeric position where search string was found

Mid(string,start,length)

chops string at a start position for a fixed number of characters.

Mid(string,start)

results in a string that has all characters before startpos removed.

Trim(string)

removes all spaces from a string.

Test the Script --> /learn/test/citystatezip.asp

<html><head>

<title>citystatezip.asp</title>

</head><body bgcolor="#FFFFFF">

<Form action = "citystatezipRespond.asp" method="post">

Enter City <b>,</b> State Zip<p>

<Input NAME="CSZ" size ="40"><p>

<Input type="submit" value="Here is my Data!">

</form>

</body></html>

The user can enter a city, state and Zip, i.e.


Rockville, MD 20849

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 11 de 142
San Fransisco, CA xxxxx
Pike's Peak, CO xxxxx
and the program can use these functions to separate the data.
<html><head>

<title>citystateziprespond.asp</title>

</head><body>

<%

alldata=request("csz")

IF instr(alldata,",")=0 THEN%>

You need a comma<br>,<br>between city and state!<p>

<%response.end

END IF

findcomma=instr(alldata,",")

city=mid(alldata,1,findcomma-1)

leftover=trim(mid(alldata,findcomma+1))

findspace=instr(leftover," ")

state=mid(leftover,1,findspace)

leftover=mid(leftover,findspace+1)

zip=leftover

response.write "city=" & city & "<br>"

response.write "state=" & state & "<br>"

response.write "zip=" & zip & "<br>"

%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 12 de 142
</body></html>

SPLIT String Function by Charles Carroll


The various string functions can be used interchangeably often. We will write the same script using
SPLIT, REPLACE and JOIN to demonstrate all 3 functions and how they often are used for similar tasks.
However, your programming situations may be especially suited for 1 out of 3 of the functions.

SPLIT(string,delimiter)

is a function that returns an array with as many elements as are separated by delimiters within the string.

The user can enter a state or multiple states. We write the program utilizing SPLIT to
demonstrate how this can be used.
statesplit.asp
Test the Script --> /learn/test/statesplit.asp

<html><head>

<title>states.asp</title>

</head><body bgcolor="#FFFFFF">

<form action="statesplitrespond.asp" method="post">

Enter State (or many states separated by <b>,<b><p>

<input NAME="states" size="40"><p>

<input type="submit" value="Get The Publishers!">

</form>

</body></html>

statesplitrespond.asp
<!--#include virtual="/learn/test/lib_dbtable.asp"-->

<html><head>

<title>statesrespond.asp</title>&

<body>

<%

mySQL="select * from publishers " & whereclause

myDSN="DSN=student;uid=student;pwd=magic"

public allstates

tempinput=request("states")

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 13 de 142
allstates=split(tempinput,",")

maxcounter=ubound(allstates)

whereclause=" where state='" & allstates(0) & "'"

FOR counter=1 TO maxcounter

thisstate=allstates(counter)

whereclause=whereclause & " OR state='" & thisstate & "'"

NEXT

mySQL=mySQL & whereclause

Call Query2Table(mySQL,myDSN)

%>

</body></html>

Replace String Functions by Charles Carroll


The various string functions can be used interchangeably often. We will write the same script using
SPLIT, REPLACE and JOIN to demonstrate all 3 functions and how they often are used for similar tasks.
However, your programming situations may be especially suited for 1 out of 3 of the functions.

REPLACE(string,oldvalue,newvalue)

results in a string that has all occurences of oldvalue replaced with a newvalue.

The user can enter a state or multiple states. We write the program utilizing REPLACE to
demonstrate how this function can be used.
statereplace.asp
Test the Script --> /learn/test/statereplace.asp

<html><head>

<title>statereplace.asp</title>

</head><body bgcolor="#FFFFFF">

<form action="statereplacerespond.asp" method="post">

Enter State (or many states separated by <b>,<b><p>

<input NAME="states" size="40"><p>

<input type="submit" value="Get The Publishers!">

</form>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 14 de 142
</body></html>

statereplacerespond.asp
<!--#include virtual="/learn/test/lib_dbtable.asp"-->

<html><head>

<title>statesrespond.asp</title>&

<body>

<%

mySQL="select * from publishers " & whereclause

myDSN="DSN=student;uid=student;pwd=magic"

tempinput=request("states")

whereclause=" where state='" & tempinput

whereclause=replace(whereclause, ",","' OR state='")

whereclause=whereclause & "'"

mySQL=mySQL & whereclause

response.write mySQL

Call Query2Table(mySQL,myDSN)

%>

</body></html>

JOIN String Functions by Charles Carroll


The various string functions can be used interchangeably often. We will write the same script using
SPLIT, REPLACE and JOIN to demonstrate all 3 functions and how they often are used for similar tasks.
However, your programming situations may be especially suited for 1 out of 3 of the functions.

JOIN(array,delimiter)

takes an array and converts it to one string with delimiters.

The user can enter a state or multiple states. We write the program using the JOIN function to
demonstrate how this function can be used.
statejoin.asp

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 15 de 142
Test the Script --> /learn/test/statejoin.asp

<html><head>

<title>statejoin.asp</title>

</head><body bgcolor="#FFFFFF">

<form action="statejoinrespond.asp" method="post">

Enter State (or many states separated by <b>,<b><p>

<input NAME="states" size="40"><p>

<input type="submit" value="Get The Publishers!">

</form>

</body></html>

statejoinrespond.asp
<!--#include virtual="/learn/test/lib_dbtable.asp"-->

<html><head>

<title>statejoinrespond.asp</title>&

<body>

<%

mySQL="select * from publishers "

myDSN="DSN=student;uid=student;pwd=magic"

public allstates

tempinput=request("states")

allstates=split(tempinput,",")

whereclause=" where state='" & JOIN(allstates, "' OR state='") & "'"

mySQL=mySQL & whereclause

response.write mySQL

Call Query2Table(mySQL,myDSN)

%>

</body></html>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 16 de 142
Arrays to store data Part #1 by Charles Carroll
Here would be a code sample without arrays:

Test the Script --> /learn/test/arraysnot.asp

<html><head>

<title>arraysnot.asp</title>

</head><body bgcolor="#FFFFFF">

<%

dim x,y,z

x=7

y=20

z=x+y

response.write z

%>

</body></html>

Here is the same example with arrays

Test the Script --> /learn/test/arrays.asp

<html><head>

<title>arrays.asp</title>

</head><body bgcolor="#FFFFFF">

<%

dim allstuff(3)

allstuff(0)=7

allstuff(1)=20

allstuff(2)=allstuff(0)+allstuff(1)

response.write allstuff(2)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 17 de 142
%>

</body></html>

http://www.activeserverpages.com/learn/subdates.asp
has a good example of arrays in a practical context.

Arrays to store data Part #2 by Charles Carroll


Assigning an array size with a variable produces a variable unless the Redim command is used.

 Method #1: You know the size

 Method #2: the size is in a variable

Test the Script --> /learn/test/arraysredim.asp

<html><head>

<title>arraysredim.asp</title>

</head><body bgcolor="#FFFFFF">

<%

' this code

dim a_array(100)

' this code will fail

x=100

dim my_array(x)

%>

</body></html>

Assigning an array size with a variable produces an error unless the Redim command is
used.
Test the Script --> /learn/test/arraysredimcorrect.asp

<html><head>

<title>arraysredimcorrect.asp</title>

</head><body bgcolor="#FFFFFF">

<%

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 18 de 142
dim my_array()

x=100

redim preserve my_array(x)

my_array(20)="Hi!"

my_array(40)="How are You"

lowcount=lbound(my_array)

highcount=ubound(my_array)

response.write "lowcount=" & lowcount & ";highcount=" & highcount & "<p>"

for counter=lowcount to highcount

response.write counter & "&nbsp;&nbsp;&nbsp;"

response.write my_array(counter) & "<br>"

next

%>

</body></html>

Arrays to store data Part 3 by Charles Carroll


There is a code intensive way to load an array and a less intensive one. For example, here is the code
intensive one:

Test the Script --> /learn/test/arraysload.asp

<html><head>

<title>arraysload.asp</title>

</head><body bgcolor="#FFFFFF">

<%

dim my_months(13)

my_months(0)=""

my_months(1)="Jan"

my_months(2)="Feb"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 19 de 142
my_months(3)="Mar"

my_months(4)="Apr"

my_months(5)="May"

my_months(6)="Jun"

my_months(7)="Jul"

my_months(8)="Aug"

my_months(9)="Sep"

my_months(10)="Oct"

my_months(11)="Nov"

my_months(12)="Dec"

lowcount=lbound(my_months)

highcount=ubound(my_months)

response.write "lowcount=" & lowcount & ";highcount=" & highcount & "<p>"

for counter=lowcount to highcount

response.write my_months(counter) & "<br>"

next

%>

</body></html>

Here is the less code intense one:


Test the Script --> /learn/test/arraysloadbest.asp

<html><head>

<title>arraysloadbest.asp</title>

</head><body bgcolor="#FFFFFF">

<%

dim my_months

my_months=array("Jan","Feb","Mar","Apr", _

"May","Jun","Jul","Aug", _

"Sep","Oct","Nov","Dec")

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 20 de 142

' finally here is how you loop through an array

lowcount=lbound(my_months)

highcount=ubound(my_months)

response.write "lowcount=" & lowcount & ";highcount=" & highcount & "<p>"

for counter=lowcount to highcount

response.write my_months(counter) & "<br>"

next

%>

</body></html>

Dictionary objects to store data by Charles Carroll


This is how to create and place items into a dictionary objects and display the contents:

Test the Script --> /learn/test/dictionarybasics.asp

<html><head>

<title>dictionarybasics.asp</title>

</head><body bgcolor="#FFFFFF">

<%

set mysample=server.CreateObject("Scripting.Dictionary")

mysample.Add "haircolor", "brown"

mysample.add "eyecolor" , "blue"

mysample.add "dateofbirth", "5/13/64"

for each whatever in mysample

response.write whatever & "="

response.write mysample.item(whatever) & "<br>"

next

set mysample=nothing

%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 21 de 142
</body></html>

This is how to make an array of dictionary objects.

Test the Script --> /learn/test/dictionaryarrays.asp

<html><head>

<title>dictionaryarrays.asp</title>

</head><body bgcolor="#FFFFFF">

<%

dim people(3)

Set people(0) = server.CreateObject("Scripting.Dictionary")

people(0).Add "fname", "Jane"

people(0).Add "lname", "Doe"

people(0).Add "haircolor", "brown"

people(0).add "eyecolor" , "blue"

people(0).add "dateofbirth", "1/10/60"

Set people(1) = server.CreateObject("Scripting.Dictionary")

people(1).Add "fname", "Reginald"

people(1).Add "mname", "Elton"

people(1).Add "lname", "Dwight"

people(1).Add "haircolor", "red"

people(1).add "eyecolor" , "dusty"

people(1).add "dateofbirth", "1/10/60"

Set people(2) = server.CreateObject("Scripting.Dictionary")

people(2).Add "fname", "Hitoshi"

people(2).Add "lname", "Yoshitsugu"

' print out one item

for each whatever in people(1)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 22 de 142
response.write whatever & "="

response.write people(1).item(whatever) & "<br>"

next

for counter=0 to 2

set people(counter)=nothing

next

%>

</body></html>

The dictionary items can be removed individually unlike array elements. See:
http://www.activeserverpages.com/docs --> vbscript docs for all the rest of the details about the
dictionary object.

Subroutines - Choosing/Validating Dates by Charles Carroll


Subroutines can be used to provide handy date entry list boxes.
Test the Script --> /learn/test/subdates.asp

<HEAD><TITLE>subdates.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<form action="subdatesrespond.asp">

Depart:

<%call showdateform("depart")%>

<br>

Arrive:

<%call showdateform("arrive")%>

<input type="submit" value="Ready To Travel">

</form>

<%

sub showdateform(mylistname)

call showmonth(mylistname)

call showday(mylistname)

call showyear(mylistname)

end sub

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 23 de 142
%>

<%sub showmonth(listname)%>

<select name="<%=listname%>month">

<%

dim monthname

monthname=array("Jan","feb","Mar","Apr", _

"May","Jun","Jul","Aug", _

"Sep","Oct","Nov","Dec")

for counter=0 to 11

temp=monthname(counter)

response.write "<option value='" & counter+1

response.write "'>" & temp & "</option>"

next%>

</select>

<%end sub%>

<%sub showday(listname)%>

<select name="<%=listname%>day">

<%for counter=1 to 31

response.write "<option>" & counter & "</option>"

next%>

</select>

<%end sub%>

<%sub showyear(listname)%>

<select name="<%=listname%>year">

<%for counter=1964 to 2005

response.write "<option>" & counter & "</option>"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 24 de 142
next%>

</select>

<%end sub%>

</BODY></HTML>

Subroutines - Choosing/Validating Dates #2 by Charles Carroll


The form handler for the previous example could validate and manipulate dates using some built-in
VBscript date handling routines, for example:

 isdate() to validate a date

<HEAD><TITLE>subdatesrespond.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

dday=request.querystring("departday")

dmonth=request.querystring("departmonth")

dyear=request.querystring("departyear")

departdate=dday & "/" & dmonth & "/" & dyear

aday=request.querystring("arriveday")

amonth=request.querystring("arrivemonth")

ayear=request.querystring("arriveyear")

arrivedate=aday & "/" & amonth & "/" & ayear

If isdate(departdate) then

response.write "Departure Date is Valid Date<br>"

else

response.write "Departure Date is INVALID<br>"

end if

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 25 de 142
If isdate(arrivedate) then

response.write "Arrival Date is Valid Date<br>"

else

response.write "Arrival Date is INVALID<br>"

end if

%>

</BODY></HTML>

Query2Table by Charles Carroll


Subroutines can save you having to repeat blocks of code. This code illustrates how we can build tables
with minimal code in the main script and by including a file with a convenient subroutine.

Test the Script --> /learn/test/subdbtable.asp

<HEAD><TITLE>subdbtable.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

mySQL="select * from publishers"

call query2table(mySQL,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

Test the Script --> /learn/test/subdbtable2.asp

<HEAD><TITLE>subdbtable2.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

mySQL="select * from titles"

call query2table(mySQL,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 26 de 142
</BODY></HTML>

Test the Script --> /learn/test/subdbtable3.asp

<HEAD><TITLE>subdbtable3.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

mySQL="select * from authors"

call query2table(mySQL,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

Test the Script --> /learn/test/subdbtable4.asp

<HEAD><TITLE>subdbtable4.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

mySQL= "SELECT Publishers.Name, Titles.Title "

mySQL= mySQL & "FROM Publishers "

mySQL= mySQL & "INNER JOIN Titles ON Publishers.PubID = Titles.PubID "

mySQL= mySQL & "order by Name"

call query2table(mySQL,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

Test the Script --> /learn/test/subdbtable5.asp

<HEAD><TITLE>subdbtable5.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 27 de 142
mySQL="select * from title_author"

call query2table(mySQL, myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

Test the Script --> /learn/test/subdbtable6.asp

<HEAD><TITLE>subdbtable6.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

mySQL="select name,type from sysobjects"

call query2table(mySQL,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

The Include file lib_dbtable.asp looks like this:

<%

sub query2table(inputquery, inputDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 28 de 142
do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

Subroutines Query2List by Charles Carroll


Subroutines can save you having to repeat blocks of code and can optionally be placed in separate files
and included when needed, thus making your pages not appear to have lots of code in-line.

Test the Script --> /learn/test/subdblist.asp

<html><head>

<TITLE>subdblist.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<form>

<%

theDSN="DSN=student;uid=student;pwd=magic"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 29 de 142
call query2list("select distinct city from publishers","cy",theDSN)

call query2list("select distinct state from publishers","st",theDSN)

call query2list("select distinct zip from publishers","zp",theDSN)

%>

</form>

<!--#include virtual="/learn/test/subdblist.inc"-->

</body></html>

The include file lib_dblist.asp looks like:

<%sub query2list(myquery,myname,myDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

set rstemp=conntemp.execute(myquery)

%>

<Select name="<%=myname%>">

<%

do while not rstemp.eof

thisfield=trim(RStemp(0))

if isnull(thisfield) or thisfield="" then

' ignore

else

response.write "<option>" & thisfield & "</option>"

end if

rstemp.movenext

loop

%>

</select>

<%rstemp.close

set rstemp=nothing

conntemp.close

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 30 de 142
set conntemp=nothing

end sub%>

Subroutines - A "Flexible Approach" by Charles Carroll


Subroutines can be very cleverly constructed so that you can use the same routine to power several
different tasks instead of copying code as the following examples illustrates!

Test the Script --> /learn/test/subreusabledataform.asp

<HEAD><TITLE>subreusabledataform.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/learn/test/subflexible.asp"-->

<%

call query2entryform("select * from publishers where pubid=16")

%>

</BODY></HTML>

Test the Script --> /learn/test/subreusabledatalist.asp

<HEAD><TITLE>subreusabledatalist.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/learn/test/lib_subflexible.asp"-->

<%

call query2list("select distinct state from publishers","thestate")

call query2list("select distinct city from publishers","thecity")

call query2list("select distinct zip from publishers","thezip")

%>

</BODY></HTML>

Test the Script --> /learn/test/subreusabledatatable.asp

<HEAD><TITLE>subreusabledatatable.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 31 de 142
<!--#include virtual="/learn/test/subflexible.asp"-->

<%

call query2table("select * from publishers")

%>

</BODY></HTML>

Test the Script --> /learn/test/subreusableform.asp

<HEAD><TITLE>subreusableform.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/learn/test/subflexible.asp"-->

<%

call query2form("select * from publishers")

%>

</BODY></HTML>

The library file lib_subflexible.asp looks like:

<%

dim htmlstart, htmlend

dim rowstart, rowend

dim fieldstart, fieldend

dim namestart, nameend

dim fieldnames

fieldnames=false

sub query2list(myquery,listname)

htmlstart="<select name='" & listname & "'>"

htmlend="</select>"

rowstart="<option>"

rowend="</option>"

fieldstart=""

fieldend=""

call query2html(myquery)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 32 de 142
end sub

sub query2table(myquery)

htmlstart="<table border=1>"

htmlend="</table>"

rowstart="<tr>"

rowend="</tr>"

fieldstart="<td valign=top>"

fieldend="</td>"

call query2html(myquery)

end sub

sub query2form(myquery)

htmlstart=""

htmlend=""

rowstart=""

rowend="<hr>"

fieldstart=""

fieldend="<br>"

fieldnames=true

namestart=""

nameend="&nbsp;=&nbsp;"

call query2html(myquery)

end sub

sub query2entryform(myquery)

htmlstart=""

htmlend=""

rowstart=""

rowend=""

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 33 de 142
fieldstart="%name%&nbsp;=&nbsp;<input type='text name='%name%' value='"

fieldend="' size='%size%'><br>"

fieldnames=false

namestart=""

nameend="&nbsp;&nbsp;="

call query2html(myquery)

end sub

sub query2html(inputquery)

set conntemp=server.createobject("adodb.connection")

conntemp.open "DSN=Student;uid=student;pwd=magic"

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1

redim fsa(howmanyfields)

redim fea(howmanyfields)

for i = 0 to howmanyfields

tempstart=replace(fieldstart,"%name%",rstemp(i).name)

tempend=replace(fieldend,"%name%",rstemp(i).name)

tempstart=replace(tempstart,"%size%",rstemp(i).actualsize)

tempend=replace(tempend,"%size%",rstemp(i).actualsize)

fsa(i)=tempstart

fea(i)=tempend

next

response.write htmlstart & vbcrlf

counter=0

do until rstemp.eof

response.write rowstart & vbcrlf

for i = 0 to howmanyfields

if fieldnames=true then

response.write namestart & rstemp(i).name & nameend

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 34 de 142
end if

response.write fsa(i) & rstemp(i) & fea(i) & vbcrlf

next

response.write rowend & vbcrlf

counter=counter+1

rstemp.movenext

if response.isclientconnected=false then

exit do

end if

loop

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

response.write htmlend

end sub

%>

Subroutines Db2list "Best" Approach by Charles Carroll


Subroutines could be considerably more useful if they took optional parameters. Since they don't we can
jury rig a system whereby a subroutine is invoked with two parameters: a delimiter and a string. And the
string itself contains the various parameters. This approach implements a more optional parameter "like"
solution.

Test the Script --> /learn/test/subdblistbest.asp

<html><head>

<TITLE>subdblistbest.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<form>

<%call db2list("^","select distinct city from publishers^city^New York")%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 35 de 142
<%call db2list("^","select distinct state from
publishers^state^NY^table^DSN=student;uid=student;pwd=magic")%>

<%call db2list("^","select distinct zip from publishers^Zip Code^^table")%>

</form>

<!--#include virtual="/learn/test/lib_dblistbest.asp"-->

The include file lib_dblistbest.asp looks like:

<%

sub db2list(mydelim,myparm)

dim myparameters

myparameters=SPLIT(myparm,mydelim)

parmcount=ubound(myparameters)

myquery=myparameters(0)

label=myparameters(1)

default=myparameters(2)

if parmcount>2 then

format=lcase(myparameters(3))

end if

if parmcount>3 then

connstring=myparameters(4)

else

connstring="DSN=Student;uid=student;pwd=magic"

end if

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 36 de 142

set conntemp=server.createobject("adodb.connection")

conntemp.open connstring

set rstemp=conntemp.execute(myquery)

If format="table" then%>

<table width="100%" border="0" cellspacing="1"><td>

<%end if

response.write label

If format="table" then%>

</td><td>

<%end if%>

<Select>

<option value="<%=default%>" selected><%=default%></option>

<%

do while not rstemp.eof %>

<option><%=RStemp(0)%></option>

<%

rstemp.movenext

loop

conntemp.close

%>

</select>

<%If format="table" then%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 37 de 142
</td><tr></table>

<%end if

end sub%>

Library of HTML Commands by Phil Paxton


©1999 by Phil Paxton (phil@matchw.com)
Subroutines and Functions can be used, for example, to provide a layer of abstraction over HTML.

Test the Script --> /learn/test/htmldemo.asp

<!--#include virtual="/learn/test/lib_htmlstuff.asp"-->

<html><head>

<title>libhtmldemo.asp by Phil Paxton</title>&

<body>

<form action="lib_htmldemorespond.asp">

<%

Call Form_TextBox("first name","Fname",20,20,"")

response.write "<br>"

Call Form_TextBox("Last Name","Lname",20,20,"")

response.write "<br>"

Call Form_TextBox("City","cy",20,20,"")

response.write "<br>"

Call Form_TextBox("State","st",2,2,"")

response.write "<br>"

Call Form_TextBox("Zip Code","zp",10,10,"")

response.write "<br>"

Call Form_SubmitButton("Register Me","register")

%>

</form>

</body>

</html>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 38 de 142
The library that enables this (named lib_htmlstuff.asp) looks like:

<%

Sub Display( Text )

Response.Write( Text )

End Sub

'----------------------------------------------------------------

Sub HTML( Text )

Response.Write( Text )

End Sub

'----------------------------------------------------------------

Sub Test( Text )

Response.Write( Text )

End Sub

'----------------------------------------------------------------

Sub Form_HiddenField( Name, Value )

HTML "<INPUT "

Form_Parm_Type "Hidden"

Form_Parm_Name Name

Form_Parm_Value Value

HTML ">"

End Sub

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 39 de 142
'----------------------------------------------------------------

Sub Form_Label( Label, Control )

If Len(Label) > 0 Then

HTML "<label "

HTML "for=" & Control

HTML ">"

HTML "<strong>"

Display Label

HTML "</strong>"

HTML "</label>"

End If

End Sub

'----------------------------------------------------------------

Sub Form_TextBox( Label, Name, MaxLength, Size, Value )

Form_Label Label, Name

HTML "<input "

Form_Parm_Type "text"

Form_Parm_Name Name

Form_Parm_Size Size

Form_Parm_ID Name

Form_Parm_MaxLength MaxLength

Form_Parm_Value Value

HTML ">"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 40 de 142

End Sub

'----------------------------------------------------------------

Sub Form_Password( Label, Name, MaxLength, Size, Value )

Form_Label Label, Name

HTML "<input "

Form_Parm_Type "password"

Form_Parm_Name Name

Form_Parm_Size Size

Form_Parm_ID Name

Form_Parm_MaxLength MaxLength

Form_Parm_Value Value

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_ScrollingText( Label, Name, Rows, Cols, Value )

Form_Label Label, Name

HTML "<textarea "

Form_Parm_Name Name

If Len(Rows) > 0 Then

HTML "rows=" & Rows & " "

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 41 de 142
End If

If Len(Cols) > 0 Then

HTML "cols=" & Cols & " "

End If

Form_Parm_ID Name

HTML ">"

If Len(Value) > 0 Then

Display Value

End If

HTML "</textarea>"

End Sub

'----------------------------------------------------------------

Sub Form_ResetButton( Name, Value )

HTML "<input "

Form_Parm_Type "reset"

Form_Parm_Value Value

Form_Parm_Name Name

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_CommandButton( Name, Value )

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 42 de 142

HTML "<input "

Form_Parm_Type "button"

Form_Parm_Value Value

Form_Parm_Name Name

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_SubmitButton( Name, Value )

HTML "<input "

Form_Parm_Type "submit"

Form_Parm_Value Value

Form_Parm_Name Name

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_RadioButton( Label, Name, Value, Checked )

HTML "<input "

Form_Parm_Type "radio"

Form_Parm_Value Value

Form_Parm_Name Name

Form_Parm_ID Name & Value

If Len(Checked) > 0 Then

If Checked Then

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 43 de 142
HTML " checked "

End If

End If

HTML ">"

Form_Label Label, Name & Value

End Sub

'----------------------------------------------------------------

Sub Form_Checkbox( Label, Name, Value, Checked )

Form_Label Label, Name

HTML "<INPUT "

Form_Parm_Type "checkbox"

Form_Parm_Name Name

Form_Parm_Value Value

If Len( Checked ) > 0 Then

If Checked = True Then

HTML " checked "

End If

End If

HTML ">"

'

End Sub

'----------------------------------------------------------------

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 44 de 142
Sub Form_Begin( Action )

HTML "<form "

HTML "method=post "

HTML "action =" & Chr(39) & Action & Chr(39) & " "

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_End( Name, Value )

Form_HiddenField Name, Value

HTML "</FORM>"

End Sub

'----------------------------------------------------------------

Sub Form_Table_Begin( Border, Width )

HTML "<table "

If Len(Border) > 0 Then

HTML "border=" & Chr(39) & Border & Chr(39) & " "

End If

Form_Parm_Width Width

HTML ">"

End Sub

'----------------------------------------------------------------

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 45 de 142

Sub Form_Table_End()

HTML "</table>"

End Sub

'----------------------------------------------------------------

Sub Form_Table_Row_Begin( Dummy, Align, VAlign )

HTML "<tr "

Form_Parm_Align Align

Form_Parm_VAlign VAlign

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_Table_Row_End( Dummy )

HTML "</tr>"

End Sub

'----------------------------------------------------------------

Sub Form_Table_Cell_Begin( Dummy, Width, Align, VAlign )

HTML "<td "

Form_Parm_Width Width

Form_Parm_Align Align

Form_Parm_VAlign VAlign

HTML ">"

End Sub

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 46 de 142
'----------------------------------------------------------------

Sub Form_Table_Cell_End( Dummy )

HTML "</td>"

End Sub

'----------------------------------------------------------------

Sub Form_ComboBox_Begin( Label, Name, Size, Multiple )

Form_Label Label, Name

HTML "<select "

Form_Parm_Name Name

Form_Parm_Size Size

If Len(Multiple) > 0 Then

If Multiple Then

HTML " multiple "

End If

End If

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_ComboBox_Item( Value, Selected )

HTML "<option "

Form_Parm_Value Value

If Len(Selected) > 0 Then

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 47 de 142
If Selected Then

HTML " selected "

End If

End If

HTML ">"

End Sub

'----------------------------------------------------------------

Sub Form_ComboBox_End()

HTML "</select>"

End Sub

'----------------------------------------------------------------

Sub Form_Title( Title )

HTML "<title>"

Display Title

HTML "</title>&

End Sub

'----------------------------------------------------------------

Sub Form_Center( Text )

HTML "<p align=" & Chr(39) & "center" & Chr(39) & ">"

Display Text

HTML "</p>"

End Sub

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 48 de 142
'----------------------------------------------------------------

Sub Form_Left( Text )

HTML "<p align=" & Chr(39) & "left" & Chr(39) & ">"

Display Text

HTML "</p>"

End Sub

'----------------------------------------------------------------

Sub Form_Right( Text )

HTML "<p align=" & Chr(39) & "right" & Chr(39) & ">"

Display Text

HTML "</p>"

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Align( Align )

If Len(Align) > 0 Then

Select Case UCase(Align)

Case "L", "LEFT"

Display " align=" & Chr(39) & "left" & Chr(39) & " "

Case "C", "CENTER"

Display " align=" & Chr(39) & "center" & Chr(39) & " "

Case "R", "RIGHT"

Display " align=" & Chr(39) & "right" & Chr(39) & " "

Case Else

End Select

End If

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 49 de 142
End Sub

'----------------------------------------------------------------

Sub Form_Parm_VAlign( VAlign )

If Len(VAlign) > 0 Then

Select Case UCase(VAlign)

Case "T", "TOP"

Display " align=" & Chr(39) & "top" & Chr(39) & " "

Case "C", "CENTER"

Display " align=" & Chr(39) & "center" & Chr(39) & " "

Case "B", "BOTTOM"

Display " align=" & Chr(39) & "bottom" & Chr(39) & " "

Case Else

End Select

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Name( Name )

If Len(Name) > 0 Then

Display " name=" & Chr(39) & Name & Chr(39) & " "

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Value( Value )

If Len(Value) > 0 Then

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 50 de 142
Display " value=" & Chr(39) & Value & Chr(39) & " "

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Type( TypeValue )

If Len(TypeValue) > 0 Then

Display " type=" & Chr(39) & TypeValue & Chr(39) & " "

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Size( Size )

If Len(Size) > 0 Then

Display " size=" & Size & " "

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_ID( ID )

If Len(ID) > 0 Then

Display " id=" & Chr(39) & ID & Chr(39) & " "

End If

End Sub

'----------------------------------------------------------------

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 51 de 142
Sub Form_Parm_MaxLength( MaxLength )

If Len(MaxLength) > 0 Then

Display " maxlength=" & MaxLength

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Length( Length )

If Len(Length) > 0 Then

Display " length=" & Length

End If

End Sub

'----------------------------------------------------------------

Sub Form_Parm_Width( Width )

If Len(Width) > 0 Then

Display " width=" & Width

End If

End Sub

'----------------------------------------------------------------

Sub Anchor_Display( TextToDisplay, HRef )

HTML "<a href=" & Chr(39) & HRef & Chr(39) & ">"

Display TextToDisplay

HTML "</a>"

End Sub

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 52 de 142
'----------------------------------------------------------------

Sub MenuItem ( TextToDisplay, HRef )

HTML "<ul>"

HTML "<li>"

HTML "<p "

Form_Parm_Align "Left"

Form_Parm_VAlign "Bottom"

HTML ">"

Anchor_Display TextToDisplay, HRef

HTML "</p>"

HTML "</li>"

HTML "</ul>"

End Sub

'----------------------------------------------------------------

Function FormatMoney( Amount )

'

' Standard constants from the MS web site but not built

' into VBScript's default constants.

'

Const TristateTrue = -1

Const TristateFalse = 0

Const TristateUseDefault = -2

'

If IsNull( Amount ) Then

FormatMoney = vbNullString

Else

FormatMoney = FormatCurrency( Amount, 2, TristateTrue _

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 53 de 142
, False, TristateTrue)

End If

'

End Function

'----------------------------------------------------------------

%>

Functions -- The WorkingDays function


This page demonstrates how to make a function and display it's results in your page.

Test the Script --> /learn/test/functionw orkingdays.asp

<title>functionworkingdays.asp</title>

<body bgcolor="#FFFFFF">

<%

response.write "3 working days from today is " & dtaddWorkingDays(now(),3) &
"<p>"

%>

2 working days from today is <%=dtaddWorkingDays(now(),2)%>

</body>

<%Function dtAddWorkingDays(dtStartDate, nDaystoAdd)

'Adds working days based on a five day week

Dim dtEndDate

Dim iLoop

'First add whole weeks

dtEndDate=DateAdd("ww",Int(nDaysToAdd/5),dtStartDate)

'Add any odd days

For iLoop = 1 To (nDaysToAdd Mod 5)

dtEndDate=DateAdd("d",1,dtEndDate)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 54 de 142
'If Saturday increment to following Monday

If WeekDay(dtEndDate)=vbSaturday Then

'Increment date to following Monday

dtEndDate=DateAdd("d",2,dtEndDate)

End If

Next

dtAddWorkingDays=dtEndDate

End Function

%>

VBScript 5 Highlights by Charles Carroll


Subroutines can save you having to repeat blocks of code. This code illustrates how we can build tables
with minimal code in the main script and by including a file with a convenient subroutine.

Eval function
Test the Script --> /learn/test/vbs5eval.asp

<html><head>

<title>vbs5eval.asp</title>

</head>

<body>

<%

x="2+2*3"

response.write eval(x)

%>

</body>

</html>

Classes:
Test the Script --> /learn/test/vbs5classes.asp

<html><head>

<title>vb5classes.asp</title>

</head>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 55 de 142
<body>

<%

' Create a myCustomer variable

Dim myCustomer

' Create a new instance of the Customer Class

' and set the value of myCustomer to be that instance

set myCustomer = new Customer

' Add a new customer

myCustomer.Add "Charles","Carroll"

' Set their Email address

myCustomer.EmailName = "charlescarroll@aspalliance.com"

' Set their credit limit

myCustomer.CreditLimit = 5000

' Display the customers fullname

response.write myCustomer.FullName

Class Customer

Public FirstName, LastName

Private nCreditLimit

Private strEmailName

Property Get EmailName

EmailName = strEmailName

End Property

Property Let EmailName ( strName)

StrEmailName = strName

End Property

Property Get FullName

FullName= FirstName & " " & LastName

End Property

Property Let CreditLimit ( s )

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 56 de 142
if s >= 0 then

nSalary = s

End If

End Property

Property Get CreditLimit

Salary = nSalary

End Property

Sub Add( First, Last )

FirstName = First

LastName = Last

End Sub

Function RaiseCreditLimit( Amount )

nCreditLimit = nCreditLimit + Amount

RaiseSalary = nSalary

End Function

End Class

%>

</body>

</html>

Execute Function:
Test the Script --> /learn/test/vbs5execute.asp

<html><head>

<title>vbs5execute.asp</title>

</head>

<body>

<%

S = "Sub Hi" & vbCrLf

S = S & " Response.write ""Hi""" & vbCrLf

S = S & "End Sub"

Execute S

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 57 de 142
Call Hi()

%>

</body>

</html>

Regular Expressions
Test the Script --> /learn/test/vbs5reg.asp

<html><head>

<title>vbs5reg.asp</title>&

<body>

<%

address="joe@aol.com"

validmail=checkemail(address)

IF validmail THEN

response.write address & " is good!"

ELSE

response.write address & " is bad!"

END IF

address="sallyaol.com"

validmail=checkemail(address)

IF validmail THEN

response.write address & " is good!"

ELSE

response.write address & " is bad!"

END IF

FUNCTION CheckEmail(parmaddress)

set myRegExp = new RegExp

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 58 de 142
' Set the pattern to check for a word followed by

' an @ followed by a word

myRegExp.pattern = "\w+\@[.\w]+"

if myRegExp.Test(parmaddress) then

CheckEmail=True

else

CheckEmail=false

end if

END FUNCTION

%>

</body>

</html>

With
Test the Script --> /learn/test/vbs5w ith.asp

<html><head>

<title>vbs5with.asp</title>

</head>

<body>

<%

with response

.write "Hi<br>"

.write "how are you doing?<br>"

.write "see you around"

end with

%>

</body>

</html>

Generic Database Display Made Easy

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 59 de 142
When you want a quick easy generic database display, go on over to:

http://www.ofifc.org/Eli/asp/homepage.asp

Here Eli Robillard has done a lot of work for you. You modify one ASP file that specifies your database
and query specs and his ASP scripts magically do the rest.

Here is an example where I make a pubs.asp designed to plug into his ASP scripts.

Test the Script --> /learn/test/genericdb/pub.asp

<%

' Generic interface to the Northwinds Employee table.

Session("dbGenericPath") = "/learn/test/genericdb/"

Session("dbExitPage") = "http://www.activeserverpages.com"

Session("dbTitle") = "Pubs"

Session("dbType") = "SQL"

Session("dbConn") = "DSN=student;uid=student;pwd=magic"

Session("dbRs") = "Publishers"

Session("dbKey") = 1

Session("dbOrder") = 2

Session("dbRecsPerPage") = 10

Session("dbFooter") = 1

Session("dbDispList") = "011101000000100010"

Session("dbDispView") = "111111111111111111"

Session("dbDispEdit") = "011111111111111111"

Session("dbSearchFields") = "011100010010001000"

Session("dbDefault6") = Date()

Session("dbCombo11") = "LIST, ??, Unknown, CA, Canada, US, United States,


DE, Denmark"

Session("dbDefault17") = 10

Session("dbWhere") = ""

Session("dbDebug") = 1

Session("dbCanEdit") = 1

Session("dbCanAdd") = 1

Session("dbCanDelete") = 1

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 60 de 142
Session("dbConfirmDelete") = 1

Session("dbViewPage") = Request.ServerVariables("PATH_INFO")

Response.Redirect Session("dbGenericPath") & "GenericList.asp"

%>

There is even a listserve supporting this great FREE script collection. It is not a general database
troubleshooting list, instead only questions concerning these wonderful scripts are allowed.

Speed/Optimization Example: A Table Display


Speeding up your scripts involves many big and small script changes. We have prepared this "before"
and "after" example to illustrate the point. This example assumes you truly have to display this many
records (for example, a corporate report). Alternatively:

 Paging records into page __ of ___ is much faster if this is appropriate

 (see /learn/dbtablepaged.asp)

 Throttling the maximum number of records if it is appropriate

 (see www.activeserverpages.com/learn/dbmaxrecs.asp)

Side note: If anyone you know believes Access queries are done asynchronously, running a couple of
these scripts will prove them wrong. Access queries execute one web user at a time sequentially.

After Optimization
Here is a very fast table display going against an identical huge SQL Server Table:

Test the Script --> /learn/test/dbtablefast.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtablefast.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN = "DSN=student;UID=student;pwd=magic"

mySQL="select * from authors order by author"

call query2table(mySQL,myDSN)

%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 61 de 142
<!--#include virtual="/learn/test/lib_dbtablefast.asp"-->

</BODY></HTML>

Here is the optimized library lib_dbtablefast.asp which achieves this speed:

<%

sub query2table(inputquery, inputDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

DO UNTIL rstemp.eof

counter=counter+1

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 62 de 142
response.write "<tr>"

for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if

response.write "<td valign=top>" & thisvalue & "</td>" & vbcrlf

next

response.write "</tr>"

rstemp.movenext

IF counter mod 50=0 THEN

If response.isclientconnected()=false THEN

EXIT DO

END IF

response.write "</table>" & TableStart

response.flush

END IF

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 63 de 142
conntemp.close

set conntemp=nothing

end sub%>

Before Optimization
Here is the original slow script which basically demonstrates techniques that may work if your data and
concurrency load is light, but the script above demonstrates the typical changes made to speed up a
script when it becomes needed or you just want to wring every ounce of speed from your site. This script
will probably timeout before it's completion!

Test the Script --> /learn/test/dbtableslow .asp

<HEAD><TITLE>dbtableslow.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN = "DSN=student;uid=student;pwd=magic"

mySQL= "SELECT * from authors order by Author"

call query2table(mySQL,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtableslow.asp"-->

</BODY></HTML>

Here is the original slow library lib_dbtableslow.asp :

<%

sub query2table(inputquery, inputDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 64 de 142
<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

DO UNTIL rstemp.eof and response.isclientconnected()%>

<tr>

<% for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

Speed/Optimization: All Variations


Fetching records in an optimized way actually has many variations. We will list most of them here, provide
code sample and typical timings for fetching and displaying records. These timings reveal an interesting
behavior. Even if a script reports it ran in say, 7 seconds, that refers to the time that script received from
the CPU. So that if 7 scripts take 8 seconds each there may be hundreds or thousands of scripts running
on the server that are sharing the CPU. User #1 may see a 7 second result in 21 seconds, so their 7
second report reflects the time spent on the server/CPU for the script and the fact that 14 seconds of
other stuff was executed round-robin with the rest of the scripts, not the time since the script started.

Method: LOOP, .movenext, periodic response.flush

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 65 de 142
Query took 6 seconds.

Query processed 10835 records.

Speed =1805.83333333333 records per second

Method: LOOP, .movenext and periodic response.flush commands. String is assembled with &
operator and writen periodically.

Query took 52 seconds.

Query processed 10835 records.

Speed =208.365384615385 records per second.

Observation: The & operator is VERY expensive! Unbelievably so.

Method: Single GetString command

Query took 4 seconds

Query processed 10837 records.

Speed =2709.25 records per second.

Method: GetRows command with no LOOP + movenext but loop through the array with periodic
response flushes.

Query took 3 seconds.

Query processed 10834 records.

Speed =3611.33333333333 records per second.

Note: Getstring often wins in many tests but it depends on many factors. I have seen a straight
loop take 18 secs where GetRows takes 9 seconds and getstring take 4 secs.

Method: GetRows command of a fixed row count (say 500 record clusters for example) with a
reponse.flush after each array is read!

Query took 3 seconds.

Query processed 10782 records.

Speed =3594 records per second.

Method: Displaying a portion of the data (say the first 500 records) only.

Query took 7 seconds.

Query processed 500 records.

Speed =71.4285714285714 records per second.

Note: This was recorded as 7 seconds but actually was much faster actually due to speed the
browser reported the results.

Now here is the code that was used to gather all the data.

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 66 de 142
Here is a table display with a simple LOOP:

Test the Script --> /learn/test/dbtableloopall.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtableLoopAll.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

<%

server.scripttimeout=240

optimize=optimize_LoopAll

myDSN = "DSN=student;UID=student;pwd=magic"

'mySQL="select * from authors order by author "

mySQL="select * from authors order by author "

Call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

Call TimerEnd

%>

</BODY></HTML>

Here is a table display with a simple LOOP assembling a string:

Test the Script --> /learn/test/dbtableloopallstring.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtableLoopAllstring.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

<%

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 67 de 142
server.scripttimeout=240

optimize=optimize_LoopAll_string

myDSN = "DSN=student;UID=student;pwd=magic"

mySQL="select * from authors order by author "

Call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

Call TimerEnd

%>

</BODY></HTML>

Here is a table display with a GetString call and no LOOP:

Test the Script --> /learn/test/dbtablegetstringall.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtablegetstringall.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

<%

server.scripttimeout=240

optimize=optimize_GetStringAll

myDSN = "DSN=student;UID=student;pwd=magic"

mySQL="select * from authors order by author"

Call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 68 de 142
response.write OptimizationName(optimize) & "<br>"

Call TimerEnd

%>

</BODY></HTML>

Here is a table display with a GetString call (buffered):

Test the Script --> /learn/test/dbtablegetstringbuffered.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtablegetstringbuffered.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

<%

server.scripttimeout=240

optimize=optimize_GetStringBuffered

myDSN = "DSN=student;UID=student;pwd=magic"

mySQL="select * from authors order by author"

Call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

response.write OptimizationName(optimize) & "<br>"

Call TimerEnd

%>

</BODY></HTML>

Here is a table display with a GetRows call and no LOOP:

Test the Script --> /learn/test/dbtablegetrow sall.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtablegetrowsall.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 69 de 142
<%

server.scripttimeout=240

optimize=optimize_getrowsall

response.write OptimizationName(optimize) & "<p>"

myDSN = "DSN=student;UID=student;pwd=magic"

mySQL="select * from authors order by author "

call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

call TimerEnd

%>

</BODY></HTML>

Here is a table display with a GetRows (buffered):

Test the Script --> /learn/test/dbtablegetrow sbuffered.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtableGetRowsBuffered.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

<%

server.scripttimeout=240

optimize=optimize_GetRowsBuffered

myDSN = "DSN=student;UID=student;pwd=magic"

'mySQL="select * from authors order by author "

mySQL="select * from authors order by author "

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 70 de 142
Call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

Call TimerEnd

%>

</BODY></HTML>

Here is a table display of a portion of the records:

Test the Script --> /learn/test/dbtablelimitrow s.asp

<%response.buffer=true%>

<HEAD><TITLE>dbtablelimitrows.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<!--#include virtual="/adovbs.inc"-->

<!--#include virtual="/learn/test/lib_dbtablefastv2.asp"-->

<%

server.scripttimeout=240

optimize=optimize_LimitRows

myDSN = "DSN=student;UID=student;pwd=magic"

mySQL="select * from authors order by author"

Call TimerStart

call query2table(mySQL,myDSN,optimize,howmany)

response.write OptimizationName(optimize) & "<br>"

Call TimerEnd

%>

</BODY></HTML>

Here is the optimized library lib_dbtablefastv2.asp which achieves this speed:

<%

Const optimize_LoopAll = 1

Const optimize_GetstringAll = 2

Const optimize_GetrowsAll = 3

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 71 de 142
Const optimize_GetrowsBuffered = 4

Const optimize_GetStringBuffered = 5

Const optimize_LimitRows = 6

Const optimize_LoopAll_String = 7

dim optimize_buffersize

dim optimize_started

dim optimize_ended

dim optimize_SQL

dim optimize_DSN

dim optimize_howmany

dim optimize_cursorlocation

dim optimize_maxrecs

dim optimize_disconnectRS

optimize_started=0

' performance stuff

optimize_buffersize=200

'optimize_cursorlocation=aduseclient

optimize_maxrecs=500

optimize_cursorlocation=aduseserver

optimize_disconnectRS=false

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 72 de 142
optimize_stringwrite=false

SUB TimerStart()

optimize_started=now()

END SUB

SUB TimerEnd()

optimize_ended=now()

elapsed=DateDiff("s", optimize_started, optimize_ended)

response.write "SQL=<b>" & optimize_SQL & "</b><br>"

response.write "DSN=<b>" & optimize_DSN & "</b><br>"

response.write "Query took <b>" & elapsed & " seconds.</b><br>"

IF optimize_howmany=-1 THEN

optimize_howmany=querycount(optimize_DSN,optimize_SQL)

END IF

response.write "Query processed <b>" & optimize_howmany & "


records.</b><br>"

response.write "Speed =<b>" & optimize_howmany/elapsed & " records per


second.</b><br>"

response.write "Notes:<br>"

pad="&nbsp;&nbsp;&nbsp;&nbsp;"

response.write pad & "buffersize=<b>" & optimize_buffersize & "</b><br>"

IF optimize_cursorlocation=adUseClient THEN

response.write pad & "cursorlocation=<b>adUseClient</b><br>"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 73 de 142
END IF

IF optimize_cursorlocation=adUseServer THEN

response.write pad & "cursorlocation=<b>adUseServer</b><br>"

END IF

END SUB

sub query2table(parmQuery, parmDSN,parmMethod,parmcount)

' method 1 = standard

' method 2 = getrows

' method 3 = getstring

dim howmany

SELECT CASE parmMethod

CASE 1

Call loopStandard(parmQuery,parmDSN,howmany)

CASE 2

Call loopGetString(parmQuery,parmDSN,howmany)

CASE 3

Call loopGetRows(parmQuery,parmDSN,howmany)

CASE 4

Call loopGetRowsBuffered(parmQuery,parmDSN,howmany)

CASE 5

Call loopGetStringBuffered(parmQuery,parmDSN,howmany)

CASE 6

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 74 de 142
Call LimitRows(parmQuery,parmDSN,howmany)

CASE 7

Call loopStandardStringWrite(parmQuery,parmDSN,howmany)

CASE ELSE

response.write "1, 2 or 3 are only valid speedmethods"

END SELECT

parmcount=howmany

If optimize_started<>0 THEN

optimize_DSN=parmDSN

optimize_SQL=parmquery

optimize_howmany=parmcount

END IF

END SUB

FUNCTION querycount(parmDSN,parmQuery)

set rstemp=Server.CreateObject("adodb.Recordset")

rstemp.open parmQuery, parmDSN, adopenstatic

querycount=rstemp.recordcount

rstemp.close

set rstemp=nothing

END FUNCTION

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 75 de 142
SUB loopstandard(inputquery, inputDSN,inputcount)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.cursorlocation=optimize_cursorlocation

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

IF optimize_disconnectRS=true THEN

conntemp.close

END IF

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

DO UNTIL rstemp.eof

counter=counter+1

response.write "<tr>"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 76 de 142
for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if

response.write "<td valign=top>" & thisvalue & "</td>" & vbcrlf

next

response.write "</tr>"

rstemp.movenext

IF counter mod 50=0 THEN

If response.isclientconnected()=false THEN

EXIT DO

END IF

response.write "</table>" & TableStart

END IF

loop%>

</table>

<%

inputcount=counter

rstemp.close

set rstemp=nothing

conntemp.close

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 77 de 142
set conntemp=nothing

END SUB%>

<%SUB loopstandardStringWrite(inputquery, inputDSN,inputcount)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.cursorlocation=optimize_cursorlocation

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

IF optimize_disconnectRS=true THEN

conntemp.close

END IF

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 78 de 142
tempSTR=""

DO UNTIL rstemp.eof

counter=counter+1

tempSTR=tempSTR & "<tr>"

for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if

tempSTR=tempSTR & "<td valign=top>" & thisvalue & "</td>" & vbcrlf

next

tempSTR=tempSTR & "</tr>"

rstemp.movenext

IF counter mod 50=0 THEN

If response.isclientconnected()=false THEN

EXIT DO

END IF

tempSTR=tempSTR & "</table>" & TableStart

response.write tempSTR

response.flush

tempSTR=""

END IF

loop%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 79 de 142
</table>

<%

inputcount=counter

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

END SUB%>

<%SUB loopGetstring(inputquery, inputDSN,inputcount)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 80 de 142
</tr>

<%

' Now lets grab all the records

tempSTR=rstemp.getstring(,, "</td><td>", "</td></tr><TR><TD>", "&nbsp;")

response.write tempSTR

response.write "</table>"

inputcount=-1

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

END SUB%>

<%SUB loopGetstringbuffered(inputquery, inputDSN,inputcount)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 81 de 142
tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col
width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<%

' Now lets grab all the records

DO

tempSTR=rstemp.getstring(,optimize_buffersize, "</td><td>",
"</td></tr><TR><TD>", "&nbsp;")

response.write tempSTR

If response.isclientconnected()=false THEN

EXIT SUB

END IF

response.write "</table>" & TableStart

LOOP UNTIL rstemp.eof

response.write "</table>"

inputcount=-1

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 82 de 142
END SUB

SUB loopGetRows(inputquery, inputDSN,inputcount)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<%

' Now lets grab all the records

alldata=rstemp.getrows

numcols=ubound(alldata,1)

numrows=ubound(alldata,2)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 83 de 142
FOR rowcounter= 0 TO numrows

FOR colcounter=0 to numcols

response.write "<td valign=top>"

response.write alldata(colcounter,rowcounter)

response.write "</td>"

NEXT

response.write "</tr>" & vbcrlf

IF rowcounter mod 50=0 THEN

If response.isclientconnected()=false THEN

EXIT FOR

END IF

response.write "</table>" & TableStart

END IF

NEXT

response.write "</table>"

inputcount=numrows

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

END SUB

SUB loopGetRowsBuffered(inputquery, inputDSN,inputcount)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 84 de 142
dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

' 0 seconds means wait forever, default is 15

conntemp.connectiontimeout=0

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<%

' Now lets grab all the records

DO

alldata=rstemp.getrows(optimize_buffersize)

numcols=ubound(alldata,1)

numrows=ubound(alldata,2)

FOR rowcounter= 0 TO numrows

FOR colcounter=0 to numcols

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 85 de 142
response.write "<td valign=top>"

response.write alldata(colcounter,rowcounter)

response.write "</td>"

NEXT

response.write "</tr>" & vbcrlf

NEXT

howmany=howmany+numrows

If response.isclientconnected()=false THEN

EXIT SUB

END IF

response.write "</table>" & TableStart

LOOP UNTIL rstemp.eof

response.write "</table>"

inputcount=howmany

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

END SUB

SUB LimitRows(inputquery, inputDSN,inputcount)

set rstemp=Server.CreateObject("adodb.Recordset")

rstemp.maxrecords=optimize_maxrecs

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 86 de 142
'rstemp.open inputquery, inputDSN, adopenforwardonly, adlockReadOnly

rstemp.open inputquery, inputDSN,adopenstatic

howmanyfields=rstemp.fields.count -1

tablestart="<table border=1 cols=3><col width='15%'><col width='70%'><col


width='15%'><tr>"

response.write tablestart

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<%

response.flush

tempSTR=rstemp.getstring(,, "</td><td>", "</td></tr><TR><TD>", "&nbsp;")

response.write tempSTR

response.write "</td></tr></table>"

inputcount=optimize_maxrecs

rstemp.close

set rstemp=nothing

END SUB

FUNCTION optimizationName(parmNum)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 87 de 142
SELECT CASE parmnum

CASE optimize_LoopAll

optimizationName="LoopAll"

CASE optimize_GetstringAll

optimizationName="GetstringAll"

CASE optimize_GetrowsAll

optimizationName="GetrowsAll"

CASE optimize_GetrowsBuffered

optimizationName="GetrowsBuffered"

CASE optimize_GetStringBuffered

optimizationName="GetStringBuffered"

CASE optimize_LimitRows

optimizationName="LimitRows"

CASE ELSE

optimizationName="undefined"

END SELECT

END FUNCTION

%>

IsClientConnected -- eliminating stray tasks by Charles Carroll


response.IsClientConnected()

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 88 de 142
is available beginning with IIS4 (if you want to see if you have it, see /learn/versioncheck.asp) and can be
used within a page to determine if the user is still fetching that page, i.e.

Test the Script --> /learn/test/infiniteloop.asp

<%server.scripttimeout=20

' this times out the script in 20 seconds whether done or not%>

<TITLE>infiniteloop.asp</TITLE>

<body bgcolor="#FFFFFF">

<%

DO

x=x+1

response.write x & "<br>"

If x=10000 then

x=1

end if

LOOP

%>

</body></html>

This loop could tie up the CPU for quite a while, even though the user hit the "stop"
button the task would still be "spinning/executing" on the server even though the user
was long gone. This is particularly true in database tasks.
Test the Script --> /learn/test/infiniteloopfixed.asp

<%server.scripttimeout=20

' this times out the script in 20 seconds whether done or

' the user hit the STOP button

%>

<TITLE>infiniteloopfixed.asp</TITLE>

<body bgcolor="#FFFFFF">

<%

DO

x=x+1

response.write x & "<br>"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 89 de 142
If x=10000 then

x=1

end if

LOOP WHILE response.isclientconnected()

%>

</body></html>

this code will stop when user hits the stop button.
I recommend that all loops through database recordsets incorporate this so that they
don't execute invisibly wasting CPU and database server resources. So here is a
database table listing script that incorporates this functionality:
Test the Script --> /learn/test/dbtableisclientconnected.asp

<TITLE>dbtableisclientconnected.asp</TITLE>

<body bgcolor="#FFFFFF">

<%

' ASP program that displays a database in table form

myDSN="DSN=Student;uid=student;pwd=magic"

mySQL="select * from publishers"

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

set rstemp=conntemp.execute(mySQL)

howmanyfields=rstemp.fields.count -1

%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name %></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 90 de 142
do until (rstemp.eof or response.isclientconnected=false)%>

<tr>

<% for i = 0 to howmanyfields%>

<td valign=top><%=rstemp(i)%></td>

<% next %>

</tr>

<%rstemp.movenext

loop

%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

%>

</body></html>

Database Full Cycle #1 --


Display Table, Edit Record, Update Record
dbfull1.asp merely displays a table like we have in other examples, except every row of the table has a
hyperlink to dbfull2.asp and passes the ID to that script in a variable called whichID. After the user edits
that information and presses submit, dbfull3.asp is called. It's task is to gather all input fields and
construct a SQL update statement. Here is a source printout of the script that displays the table and
"starts the ball rolling":

<%

response.buffer=true

Response.ExpiresAbsolute = Now() - 1

Response.AddHeader "Cache-Control", "private"

%>

<html><head>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 91 de 142
<title>authorshow.asp</title>

<meta http-equiv="pragma" content="no-cache">

</head><body bgcolor="#FFFFFF">

<%

myDSN="DSN=Student;uid=student;pwd=magic"

mySQL="select * from authors where AU_ID<100 order by author"

IDfield="AU_ID"

scriptresponder="authoredit.asp"

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

set rstemp=conntemp.execute(mySQL)

howmanyfields=rstemp.fields.count -1

%>

<table border="1">

<tr>

<td valign="top">---</td>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name %></b></td>

<% next %>

</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr><td valign="top">

<%my_link=scriptresponder & "?which=" & rstemp(idfield)%>

<a HREF="<%=my_link%>">Edit</a></td>

<% for i = 0 to howmanyfields%>

<td valign="top"><%=rstemp(i)%></td>

<% next %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 92 de 142
</tr>

<%

rstemp.movenext

loop

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

%>

</table></body></html>

Database Full Cycle #2 --


Display Table, Edit Record, Update Record
Here is the script that shows one record based on being linked to from the table

html><head>

<title>authoredit.asp</title>

</head><body bgcolor="#FFFFFF">

<%

' My ASP program that given an AU_ID, allows editing a record

myDSN="DSN=Student;uid=student;pwd=magic"

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

form_ID=request.querystring("which")

sqltemp="select * from authors "

sqltemp=sqltemp & " where AU_ID=" & form_id

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 93 de 142

set rstemp=conntemp.execute(sqltemp)

form_auID=rstemp("AU_ID")

form_author=rstemp("Author")

form_year_born=rstemp("Year_Born")

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

%>

<body>

<form name="myauthor" action="authoreditrespond.asp" method="POST">

<input type="hidden" name="id" value="<%=form_auid%>">

<p>Author ID: <%=form_auid%></p>

<p> Author Name:

<input type="TEXT" name="name" value="<%=form_author%>"></p>

<p> Year Born:

<input type="TEXT" name="year" value="<%=form_year_born%>"></p>

<p> <input type="SUBMIT"> </p>

</form>

</body>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 94 de 142
Database Full Cycle #3 --
Display Table, Edit Record, Update Record
Here is the script that updates one record after the submit button is pushed on the previous script.

<body bgcolor="#FFFFFF"></HEAD>

<%

on error resume next

form_name=request.form("name")

form_year=request.form("year")

form_ID=request.form("ID")

Set Conn = Server.CreateObject("ADODB.Connection")

conn.open "DSN=Student;uid=student;pwd=magic"

' change apostrophe to double apostrophe

form_name=Replace(form_name, "'", "''")

SQLstmt = "UPDATE authors SET "

SQLStmt = SQLstmt & "Author='" & form_name & "',"

SQLstmt = SQLstmt & "year_born=" & form_year

SQLStmt = SQLStmt & " WHERE AU_ID=" & form_id

Set RS = Conn.Execute(SQLStmt)

If err.number>0 then

response.write "VBScript Errors Occured:" & "<P>"

response.write "Error Number=" & err.number & "<P>"

response.write "Error Descr.=" & err.description & "<P>"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 95 de 142
response.write "Help Context=" & err.helpcontext & "<P>"

response.write "Help Path=" & err.helppath & "<P>"

response.write "Native Error=" & err.nativeerror & "<P>"

response.write "Source=" & err.source & "<P>"

response.write "SQLState=" & err.sqlstate & "<P>"

end if

IF conn.errors.count> 0 then

response.write "Database Errors Occured" & "<P>"

response.write SQLstmt & "<P>"

for counter= 0 to conn.errors.count

response.write "Error #" & conn.errors(counter).number & "<P>"

response.write "Error desc. -> " & conn.errors(counter).description &


"<P>"

next

else

response.write "<B>Everything Went Fine. Record is updated now!</b>"

response.write "<br>" & SQLstmt

end if

rs.close

set rs=nothing

Conn.Close

set conn=nothing

%>

</BODY>

</HTML>

Database -- Convert to Comma-Delimited File by Charles Carroll


This page demonstrates the capabilities how to write an ASCII comma-delimited file from a SQL
statement.

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 96 de 142
<html><head>

<TITLE>dbconvert.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<%

whichname="/upload/tests/authors.txt"

myDSN="DSN=Student;uid=student;pwd=magic"

mySQL="select * from authors where au_id<100"

showblank=""

shownull="<null>"

linestart=chr(34)

lineend=chr(34)

delimiter=chr(34) & "," & chr(34)

delimitersub=""

whichFN=server.mappath(whichname)

Set fstemp = server.CreateObject("Scripting.FileSystemObject")

Set filetemp = fstemp.CreateTextFile(whichFN, true)

' true = file can be over-written if it exists

' false = file CANNOT be over-written if it exists

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

set rstemp=conntemp.execute(mySQL)

' this code detects if data is empty

If rstemp.eof then

response.write "No data to convert for SQL statement<br>"

response.write mySQL & "<br>"

connection.close

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 97 de 142
set connection=nothing

response.end

end if

DO UNTIL rstemp.eof

thisline=linestart

for each whatever in rstemp.fields

thisfield=whatever.value

if isnull(thisfield) then

thisfield=shownull

end if

if trim(thisfield)="" then

thisfield=showblank

end if

thisfield=replace(thisfield,delimiter,delimitersub)

thisline=thisline & thisfield & delimiter

next

tempLen=len(thisline)

tempLenDelim=len(delimiter)

thisline=mid(thisline,1,tempLEN-tempLenDelim) & lineend

filetemp.WriteLine(thisline)

' response.write thisline & "<br>"

rstemp.movenext

LOOP

filetemp.Close

set filetemp=nothing

set fstemp=nothing

rstemp.close

set rstemp=nothing

conntemp.close

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 98 de 142
set conntemp=nothing

If err.number=0 then

response.write "File was converted sucessfully!<br>"

response.write "Converted file is at <a href='"

response.write whichname & "'>" & whichname & "</a>"

else

response.write "VBScript Errors Occured!<br>"

response.write "Error Number=#<b>" & err.number & "</b><br>"

response.write "Error Desc. =<b>" & err.description & "</b><br>"

response.write "Help Path =<b>" & err.helppath & "</b><br>"

response.write "Native Error=<b>" & err.nativeerror & "</b><br>"

response.write "Error Source =<b>" & err.source & "</b><br>"

response.write "SQL State=#<b>" & err.sqlstate & "</b><br>"

end if

%>

</body></html>

Database -- Delete Record with SQL statement


SQL statements can be used to delete data as well.

Here is a script that will add a bunch of records with the AU_ID of 200:

<TITLE>dbaddmany.asp</TITLE>

<body bgcolor="#FFFFFF">

<HTML>

<!--#include file="lib_errors.asp"-->

<%

on error resume next

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 99 de 142
myDSN = "DSN=Student;uid=student;pwd=magic"

mySQL = "INSERT INTO authors (AU_ID,author,year_born) "

mySQL = mySQL & "VALUES (200,'Charles M. Carroll',1964)"

Set Conn = Server.CreateObject("ADODB.Connection")

conn.open myDSN

for counter=1 to 200

thistask="Task #" & counter & "<br>"

response.write thistask

Conn.Execute(mySQL)

Call ErrorVBScriptReport(thistask)

Call ErrorADOReport(mySQL,conn)

next

Conn.Close

set conn=nothing

%>

</BODY>

</HTML>

Now here is a script that will delete all the records the above script added:

Test the Script --> /learn/test/dbdeletemany.asp

<TITLE>dbdeletemany.asp</TITLE>

<body bgcolor="#FFFFFF">

<HTML>

<!--#include file="lib_errors.asp"-->

<%

on error resume next

myDSN = "DSN=Student;uid=student;pwd=magic"

mySQL = "DELETE FROM authors WHERE au_id=200"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 100 de 142
Set Conn = Server.CreateObject("ADODB.Connection")

conn.open myDSN

Conn.Execute mySQL,howmany

response.write "The statement " & mySQL & "<b> deleted " & howmany & "
records</b><br>"

Call ErrorVBScriptReport("Deleting...")

Call ErrorADOReport(mySQL,conn)

Conn.Close

set conn=nothing

%>

</BODY>

</HTML>

Count Query/Table Records by Juan Llibre, Charles Carroll


This script counts the records in a database. Many people who attempt to use the .recordcount property
have the value -1 returned to them. In a nutshell, -1 means "I don't know how many records this
query/table contains". It happens since the default cursortype is AdOpenforwardonly (see below for
explanation of all cursor types).

The critical part here is having a cursor that supports it and including adovbs.inc to define the cursor
types. The file adovbs.inc can be obtained from http://www.learnasp.com/adovbs.inc

Adopenstatic cursor

The data is dead. If you retrieve a million records for example at 9:00am and it takes 6 minutes to read
the data, at the 6th minute you will not be retrieving fresh or recently added data. It is like a snapshot of
the data. Recordsets opened this way WILL contain an accurate recordcount.

Adopenforwardonly cursor (the default)

The data is alive but you can only move forward. Attempts to move backward or to specific record
numbers will fail.. Recordsets opened this way WILL NOT contain an accurate recordcount, instead
returning -1.

Adopenkeyset cursor

The data is alive and any record read will be the most recent data. f you retrieve a million records for
example at 9:00am and it takes 6 minutes to read the data, at the 6th minute you will still be retrieving
fresh data but NOT data added or deleted since 9am. Recordsets opened this way WILL NOT contain an
accurate recordcount, instead returning -1.

Adopendynamic cursor

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 101 de 142
The data is alive and additions will be noticed. If you retrieve a million records for example at 9:00am
and it takes 6 minutes to read the data, at the 6th minute you will still be retrieving fresh data and records
added to the end of the data. Recordsets opened this way WILL contain an accurate recordcount.

Here is the script that counts the query results:

Test the Script --> /learn/test/dbcount.asp

<head><html>

<TITLE>dbcount.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<!--#INCLUDE VIRTUAL="/ADOVBS.INC" -->

<%

' change these for your site

connectme="DSN=Student;uid=student;pwd=magic"

sqltemp="select * from publishers where state='NY'"

set rstemp=Server.CreateObject("adodb.Recordset")

rstemp.open sqltemp, connectme, adopenstatic

howmanyrecs=rstemp.recordcount

response.write howmanyrecs & " records in<br>" & sqltemp

rstemp.close

set rstemp=nothing

%>

</body></html>

It is also important to understand that any situation where you open the database and are able to obtain
an accurate record count is by nature slower than opening a database that also has the burden of
knowing how many records it has upon demand. The additional overhead and limitations of a
adopendynamic or adopenstatic cursor may be a poor way to retrieve the data because the recordset
even though they count accurately. If you must count AND retrieve, I recommend counting first, closing
the recordset and then re-opening the recordset with the best cursor for speed.

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 102 de 142
ADO Cursor Types by Phil Paxton (juggler@iquest.net)
ADO cursor types affects the properties and methods that are available as this table illustrates.

Property Forward-Only Dynamic Keyset Static


AbsolutePage N/A N/A R/W R/W
AbsolutePosition N/A N/A R/W R/W
ActiveConnection R/W R/W R/W R/W
BOF R/O R/O R/O R/O
Bookmark N/A N/A R/W R/W
CacheSize R/W R/W R/W R/W
CursorLocation R/W R/W R/W R/W
CursorType R/W R/W R/W R/W
EditMode R/O R/O R/O R/O
EOF R/O R/O R/O R/O
Filter R/W R/W R/W R/W
LockType R/W R/W R/W R/W
MarshalOptions R/W R/W R/W R/W
MaxRecords R/W R/W R/W R/W
PageCount N/A N/A R/O R/O
PageSize R/W R/W R/W R/W
RecordCount N/A N/A R/O R/O
Source R/W R/W R/W R/W
State R/O R/O R/O R/O
Status R/O R/O R/O R/O
Method
AddNew Yes Yes Yes Yes
CancelBatch Yes Yes Yes Yes
CancelUpdate Yes Yes Yes Yes
Clone N/A N/A Yes Yes
Close Yes Yes Yes Yes
Delete Yes Yes Yes Yes
GetRows Yes Yes Yes Yes
Move Yes Yes Yes Yes
MoveFirst Yes Yes Yes Yes
MoveLast N/A Yes Yes Yes
MoveNext Yes Yes Yes Yes
MovePrevious N/A Yes Yes Yes
NextRecordset Yes Yes Yes Yes
Open Yes Yes Yes Yes

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 103 de 142
Requery Yes Yes Yes Yes
Resync N/A N/A Yes Yes
Supports Yes Yes Yes Yes
Update Yes Yes Yes Yes
UpdateBatch Yes Yes Yes Yes

Legend:
R/W = Read/Write
R/O = Read-Only
N/A = Not Available or Supported
Yes = Available/Supported

Database -- Form to Input a New Record


This page demonstrates the capabilities how to setup a simple form for a new database record. The
script:

Test the Script --> /learn/test/dbnew rec.asp

<html><head>

<title>dbnewrec.asp</title>&

<body bgcolor="#FFFFFF">

<% ' My ASP program that allows you to append a record %>

<form name="myauthor" action="dbnewrecSQL.asp" method="GET">

<p>Author ID: <input type="TEXT" name="id"></p>

<p> Author Name: <input type="TEXT" name="name"></p>

<p> Year Born: <input type="TEXT" name="year"></p>

<p> <input type="SUBMIT"> </p>

</form></body></html>

Database -- Add New Record with SQL statement


This page demonstrates the capabilities how to add a record to a database with a SQL statement. To
double check it is in the database try: Test This -->/learn/test/db1parm.asp?id=9000

If the script doesn't work when adapting it to YOUR database, see:

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 104 de 142
http://www.activeserverpages.com/learn/dbtroubleshoot.asp to determine what the trouble is.

The script is:


Test This -->/learn/test/dbnewrecSQL.asp?name=Joey&id=9000&year=1964
<TITLE>dbnewrecSQL.asp</TITLE>

<body bgcolor="#FFFFFF">

<HTML>

<%

'on error resume next

auname=request.querystring("name")

auyear=request.querystring("year")

auID=request.querystring("ID")

If auid<9000 then

auid=auid+9000

end if

Set Conn = Server.CreateObject("ADODB.Connection")

conn.open "DSN=Student;uid=student;pwd=magic"

SQLStmt = "INSERT INTO authors (AU_ID,author,year_born) "

SQLStmt = SQLStmt & "VALUES (" & auid

SQLStmt = SQLStmt & ",'" & auname & "'"

SQLStmt = SQLStmt & "," & int(auyear) & ")"

Set RS = Conn.Execute(SQLStmt)

set rs=nothing

If err.number>0 then

response.write "VBScript Errors Occured:" & "<P>"

response.write "Error Number=" & err.number & "<P>"

response.write "Error Descr.=" & err.description & "<P>"

response.write "Help Context=" & err.helpcontext & "<P>"

response.write "Help Path=" & err.helppath & "<P>"

response.write "Native Error=" & err.nativeerror & "<P>"

response.write "Source=" & err.source & "<P>"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 105 de 142
response.write "SQLState=" & err.sqlstate & "<P>"

else

response.write "No VBScript Errors Occured" & "<P>"

end if

IF conn.errors.count> 0 then

response.write "Database Errors Occured" & "<br>"

response.write "<b>" & SQLstmt & "</b><P>"

for counter= 0 to conn.errors.count

response.write "Error #" & conn.errors(counter).number & "<P>"

response.write "Error desc. -> " & conn.errors(counter).description &


"<P>"

next

else

response.write "No Database Errors Occured!" & "<P>"

end if

Conn.Close

set conn=nothing

%>

</BODY>

</HTML>

Add New Record with ADO


This page demonstrates the capabilities how to add a record to a database using ADO instead of SQL.
The script is:

Test the Script --> /learn/test/dbnew ado.asp

<html><head>

<title>dbnewrec.asp</title>&

<body bgcolor="#FFFFFF">

<% ' My ASP program that allows you to append a record %>

<form name="myauthor" action="dbnewADOrespond.asp" method="GET">

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 106 de 142
<p>Author ID: <input type="TEXT" name="id"></p>

<p> Author Name: <input type="TEXT" name="name"></p>

<p> Year Born: <input type="TEXT" name="year"></p>

<p> <input type="SUBMIT"> </p>

</form></body></html>

The form responder looks like this:

<TITLE>dbnewADO.asp</TITLE>

<body bgcolor="#FFFFFF">

<HTML>

<!--#INCLUDE VIRTUAL="/ADOVBS.INC" -->

<%

'on error resume next

auname=request.querystring("name")

auyear=request.querystring("year")

auID=request.querystring("ID")

If auid<9000 then

auid=auid+9000

end if

conn="DSN=Student;uid=student;pwd=magic"

Set RS = Server.CreateObject("ADODB.Recordset")

RS.Open "authors",Conn,adopenstatic,adlockoptimistic

RS.AddNew

RS("AU_ID")=auid

RS("Author") = auname

RS("Year_Born")= int(auyear)

RS.Update

RS.Close

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 107 de 142
set rs=nothing

If err.number>0 then

response.write "VBScript Errors Occured:" & "<P>"

response.write "Error Number=" & err.number & "<P>"

response.write "Error Descr.=" & err.description & "<P>"

response.write "Help Context=" & err.helpcontext & "<P>"

response.write "Help Path=" & err.helppath & "<P>"

response.write "Native Error=" & err.nativeerror & "<P>"

response.write "Source=" & err.source & "<P>"

else

response.write "Record was added Fine!<P>"

end if

%>

</BODY>

</HTML>

Database -- Use GetString to speed code by Charles Carroll


This page demonstrates the capabilities how to use getstring (part of ADO 2.0 or above, if you are not
sure what ADO version is on your server, see /learn/versioncheck.asp)

 to display a table from a SQL statement with one call

 eliminate multiple response.writes

 eliminate do until eof tests.

The script to display the table utilizing getstring is:

Test the Script --> /learn/test/dbtablegetstring.asp

<!--#INCLUDE VIRTUAL="/ADOVBS.INC" -->

<TITLE>dbtablegetstring.asp</TITLE>

<body bgcolor="#FFFFFF">

<%

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 108 de 142
whichDSN="DSN=Student;uid=student;pwd=magic"

whichtable="publishers"

' ASP program that displays a database in table form

set conntemp=server.createobject("adodb.connection")

conntemp.open whichDSN

set rstemp=server.createobject("adodb.recordset")

rstemp.open whichtable, conntemp, adopenforwardonly, _

adlockReadOnly, adCmdTable

response.write "<table border=1><TR><TD>"

tempSTR=rstemp.getstring(,, "</td><td>", "</td></tr><TR><TD>", "&nbsp;")

response.write tempSTR

response.write "</td></tr></table>"

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

%>

</body></html>

A similar script to display a list box utilizing getstring is:

Test the Script --> /learn/test/dblistgetstring.asp

<!--#INCLUDE VIRTUAL="/ADOVBS.INC" -->

<html><head>

<TITLE>dblistgetstring.asp</TITLE>&

<body bgcolor="#FFFFFF">

<%

' ASP program that displays a database in list form

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 109 de 142
myDSN="DSN=Student;uid=student;pwd=magic"

mySQL="select distinct state from publishers"

set conntemp=server.createobject("adodb.connection")

conntemp.open "DSN=Student;uid=student;pwd=magic"

' Const adCmdUnknown, adCmdText, adCmdTable (no) , adCmdStoredProc

set rstemp=server.createobject("adodb.recordset")

rstemp.open mySQL, conntemp, adopenforwardonly, _

adlockReadOnly, adCmdUnknown

response.write "<form><select name='state'><option>"

tempSTR=rstemp.getstring(,, "", "</option><option>", "&nbsp;")

response.write tempSTR

response.write "</select></form>"

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

%>

</body></html>

Listing Tables within Databases by Charles Carroll DRAFT


SQL Server allows you to list tables like this:

Test the Script --> /learn/test/sqlservertablelist.asp

<HEAD><TITLE>sqlservertablelist.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 110 de 142
<%

whichDSN="DSN=student;uid=student;pwd=magic"

call query2table("select name,type from sysobjects where type='U'", whichDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

Access allows you to list tables like this (assuming you allow system objects to be
visible within the database on the Access side):
Test the Script --> /learn/test/accesstablelist.asp

<HEAD><TITLE>accesstablelist.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

whichDSN="DRIVER={Microsoft Access Driver (*.mdb)}; "

whichDSN=whichDSN & "DBQ=" & server.mappath("/learn/test/biblio.mdb")

call query2table("select * from MsysObjects WHERE type = 1",whichDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

The Include file looks like this:


<%

sub query2table(inputquery, inputDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 111 de 142
<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

ADO Schemas to list tables & fields


You can examine a Schema for the table names and column names and column detail information.

Test the Script --> /learn/test/dbschemas.asp

<html><head>

<TITLE>dbschemas.asp</TITLE>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 112 de 142
</head>

<body bgcolor="#FFFFFF">

<!--#INCLUDE VIRTUAL="/ADOVBS.INC" -->

<!--#INCLUDE VIRTUAL="/learn/test/lib_fieldtypes.asp" -->

<%

myDSN="DSN=Student;uid=student;pwd=magic"

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

Set rsSchema = conntemp.OpenSchema(adSchemaColumns)

thistable=""

pad="&nbsp;&nbsp;&nbsp;"

DO UNTIL rsSchema.EOF

prevtable=thistable

thistable=rsSchema("Table_Name")

thiscolumn=rsSchema("COLUMN_NAME")

IF thistable<>prevtable THEN

response.write "Table=<b>" & thistable & "</b><br>"

response.write "TABLE_CATALOG=<b>" & rsSchema("TABLE_CATALOG") &


"</b><br>"

response.write "TABLE_SCHEMA=<b>" & rsSchema("TABLE_SCHEMA") & "</b><p>"

END IF

response.write "<br>" & pad & "Field=<b>" & thiscolumn & "</b><br>"

response.write pad & "Type=<b>" & fieldtypename(rsSchema("DATA_TYPE")) &


"</b><br>"

DIM colschema(27)

colschema(0)="TABLE_CATALOG"

colschema(1)="TABLE_SCHEMA"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 113 de 142
colschema(2)="TABLE_NAME"

colschema(3)="COLUMN_NAME"

colschema(4)="COLUMN_GUID"

colschema(5)="COLUMN_PROP_ID"

colschema(6)="ORDINAL_POSITION"

colschema(7)="COLUMN_HASDEFAULT"

colschema(8)="COLUMN_DEFAULT"

colschema(9)="COLUMN_FLAGS"

colschema(10)="IS_NULLABLE"

colschema(11)="DATA_TYPE"

colschema(12)="TYPE_GUID"

colschema(13)="CHARACTER_MAXIMUM_LENGTH"

colschema(14)="CHARACTER_OCTET_LENGTH"

colschema(15)="NUMERIC_PRECISION"

colschema(16)="NUMERIC_SCALE"

colschema(17)="DATETIME_PRECISION"

colschema(18)="CHARACTER_SET_CATALOG"

colschema(19)="CHARACTER_SET_SCHEMA"

colschema(20)="CHARACTER_SET_NAME"

colschema(21)="COLLATION_CATALOG"

colschema(22)="COLLATION_SCHEMA"

colschema(23)="COLLATION_NAME"

colschema(24)="DOMAIN_NAME"

colschema(25)="DOMAIN_CATALOG"

colschema(26)="DOMAIN_SCHEMA"

colschema(27)="DESCRIPTION"

ON ERROR RESUME NEXT

FOR counter=4 to 27

thisColInfoType=colschema(counter)

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 114 de 142
thisColInfo=rsSchema(thisColInfoType)

If err.number<>0 then

thiscolinfo="-error-"

err.clear

END IF

IF thisColInfo<>"" THEN

response.write pad & pad & pad & thiscolinfotype

response.write "=<b>" & thiscolinfo & "</b><br>"

END IF

NEXT

response.flush

rsSchema.MoveNext

LOOP

rsSchema.Close

set rsSchema=nothing

conntemp.close

set conntemp=nothing

%>

</body></html>

Here is the contents of lib_fieldtypes.asp which is included to make this example work:

<%

FUNCTION fieldtypename(parm1)

SELECT CASE Parm1

CASE 0

fieldtypename="adEmpty"

CASE 16

fieldtypename="adTinyInt"

CASE 2

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 115 de 142
fieldtypename="adSmallInt"

CASE 3

fieldtypename="adInteger"

CASE 20

fieldtypename="adBigInt"

CASE 17

fieldtypename="adUnsignedTinyInt"

CASE 18

fieldtypename="adUnsignedSmallInt"

CASE 19

fieldtypename="adUnsignedInt"

CASE 21

fieldtypename="adUnsignedBigInt"

CASE 4

fieldtypename="adSingle"

CASE 5

fieldtypename="adDouble"

CASE 6

fieldtypename="adCurrency"

CASE 14

fieldtypename="adDecimal"

CASE 131

fieldtypename="adNumeric"

CASE 11

fieldtypename="adBoolean"

CASE 10

fieldtypename="adError"

CASE 132

fieldtypename="adUserDefined"

CASE 12

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 116 de 142
fieldtypename="adVariant"

CASE 9

fieldtypename="adIDispatch"

CASE 13

fieldtypename="adIUnknown"

CASE 72

fieldtypename="adGUID"

CASE 7

fieldtypename="adDate"

CASE 133

fieldtypename="adDBDate"

CASE 134

fieldtypename="adDBTime"

CASE 135

fieldtypename="adDBTimeStamp"

CASE 8

fieldtypename="adBSTR"

CASE 129

fieldtypename="adChar"

CASE 200

fieldtypename="adVarChar"

CASE 201

fieldtypename="adLongVarChar"

CASE 130

fieldtypename="adWChar"

CASE 202

fieldtypename="adVarWChar"

CASE 203

fieldtypename="adLongVarWChar"

CASE 128

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 117 de 142
fieldtypename="adBinary"

CASE 204

fieldtypename="adVarBinary"

CASE 205

fieldtypename="adLongVarBinary"

CASE ELSE

fieldtypename="Undefined by ADO"

END SELECT

END FUNCTION

%>

Troubleshooting SQL Statements (by Charles Carroll)


Now we will show some SQL statements (below) with mistakes and the fixes indicated in red to show how
to make the statements work. The kind of fixes we deploy include:

 text fields must have single quotes around the values.

 fields with spaces in their names must be surrounded with []

 set parameters must have commas between them

Text fields with single quote ' cannot be placed into SQL statements unmodified. Notice how the last
example below uses the VBScript replace command to transform a string that may contain embedded ' .
Statement with Flaws Improved Statement (fixes in red)
added space before SET
UPDATE mytableSET UPDATE mytable SET
LocID=0007,Material=13 1/4 LocID='0007',Material='13 1/4',
Description=T-shirts ListPrice=35 WHERE Description='T-shirts', [List Price]=35
CusID=97 WHERE CusID=97
INSERT INTO authors (AU_ID, author, INSERT INTO authors (AU_ID, author,
year_born) VALUES (7000, Joe year_born) VALUES (7000, 'Joe
Smith,1950) Smith',1950)
SELECT * from atable where state = MD SELECT * from atable where state = 'MD'
and and
year born<1955 and [year born]<1955
<% <%
key=request.querystring("id") key=request.querystring("id")
au=request.querystring("author") au=request.querystring("author")
birthyear=request.querystring("year") au=Replace(au, "'", "''")
SQLstmt="INSERT INTO authors (AU_ID, birthyear=request.querystring("year")
author, year_born) VALUES (" SQLstmt="INSERT INTO authors (AU_ID,
SQLstmt= SQLstmt & key & "," author, year_born) VALUES ("
SQLstmt= SQLstmt & author & "," SQLstmt= SQLstmt & key & ",'"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 118 de 142
SQLstmt= SQLstmt & author & "',"
SQLstmt= SQLstmt & birthyear & ")"
SQLstmt= SQLstmt & birthyear & ")"
%>
%>

Displaying A Table/User Supplied Query Input


This page demonstrates the capabilities how to display a table from a SQL statement using one input
variable from a user. The script to display a specified record in the table is:

Test This -->/learn/test/db1parm.asp?id=100


<TITLE>db1parm.asp</TITLE>

<body bgcolor="#FFFFFF">

<%

' My ASP program that talks to a database

set conntemp=server.createobject("adodb.connection")

conntemp.open "DSN=Student;uid=student;pwd=magic"

p1=request.querystring("ID")

temp="select * from authors where AU_ID=" & p1

set rstemp=conntemp.execute(temp)

howmanyfields=rstemp.fields.count -1

%>

<table border=1>

<tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name %></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields%>

<td valign=top><% = rstemp(i) %></td>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 119 de 142
<% next %>

</tr>

<% rstemp.movenext

loop

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing%>

</table>

</body>

</html>

Search Database #2 (SQL Where clause examples)


For our next examples, knowing the structures of the tables will be helpful.

The authors database has a structure like this:

Au_ID Author Year_Born

The titles database has a structure like this:

Title Year_Published ISBN PubID Description Notes Subject Comments

The Title_Author table looks like this:

ISBN Au_ID

The publisher' database has a structure like this:

PubID Name Company_Name Address City State Zip Telephone Fax Comments

Search Database #1 (SQL Where clauses)


There are several ways to search the data using pure SQL once we review the simple rules of how a
WHERE clause works.

 Text fields must be enclosed in single quotes, i.e.

 "select * from publishers where state='MD'

 Numeric fields need no special characters before and after

 "select * from publishers where PubID=10"

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 120 de 142
 If you aren't sure how to spell the text field or are looking for sound alikes, LIKE supports %%
wildcards

 "select * from publishers where Name like 'A%%'"

These basic WHERE clause guidelines above are the fundamental building block of searches.

It is also helpful to utilize the equality operators, i.e.

<> not equal

> greater than

< less than

>= greater than OR equal

<= less than or equal

 Numeric fields benefit most from the equality operators:

 "select * from publishers where PubID>10"

SQL Where Examples by Charles Carroll


Here are some where statements and their results.

Test the Script --> /learn/test/sqlw here1.asp

<HEAD><TITLE>SQLwhere1.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select * from publishers where name like 'A%%'")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

Test the Script --> /learn/test/sqlw here2.asp

<HEAD><TITLE>SQLwhere2.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select * from titles where Year_Published >= 1994")

%>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 121 de 142
<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

Test the Script --> /learn/test/sqlw here3.asp

<HEAD><TITLE>SQLwhere3.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select * from publishers where fax like '212%%'")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

Test the Script --> /learn/test/sqlw here4.asp

<HEAD><TITLE>sqlwhere4.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select * from publishers where state<> 'NY'")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

The Include file looks like this:

<%

sub query2table(inputquery)

set conntemp=server.createobject("adodb.connection")

conntemp.open "DSN=Student;uid=student;pwd=magic"

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 122 de 142
</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

Search Database (SQL Where Form examples)


In the previous page we introduced the WHERE clause, but now we will see several examples of the
WHERE clause in typical forms. This example allows users to choose a city:

Test the Script --> /learn/test/sqlw hereform1.asp

<HEAD><TITLE>sqlwhereform1.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<Form action = "sqlwhereForm1respond.asp" method=GET>

Choose A State:<p>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 123 de 142
State: <Input NAME="st" MaxLength="2" size="3"><P>

<Input type="submit" value="Get Data">&nbsp;<Input type="reset" value="Clear


State"></form>

</BODY></HTML>

<HEAD><TITLE>sqlwhereform1respond.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

myDSN="DSN=student;uid=student;pwd=magic"

mystate=request.querystring("st")

SQLtemp="select * from publishers where state='"

SQLtemp=SQLtemp & mystate & "'"

call query2table(SQLtemp,myDSN)

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

The file lib_subdbtable.asp looks like this:


<%

sub query2table(inputquery, inputDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 124 de 142
</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

SQL OR Search Example by Charles Carroll


AND and OR operators expand the power of the WHERE clause and provide a powerful tool to check
multiple conditions. The Basic Guidelines are as follows:

If your goal is that several if conditions must ALL BE TRUE to suceed, this is the Role of the AND within a
WHERE clause, i.e.

"select * from publishers where state='MD' and city='Rockville'

"select * from authors where Year_Born>1960 and Year_Born<1970'
If several conditions can indivually be true this is the Role of an OR within a WHERE clause, i.e.

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 125 de 142
"select * from publishers where state='MD' OR state='NY'
Test the Script --> /learn/test/sqlcities.asp

<HEAD><TITLE>SQLcities.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<Form action = "SQLcitiesrespond.asp" method="POST">

Choose City (or Cities):<p>

<%

call query2listm("select distinct city from publishers", _

"cy","DSN=student;uid=student;pwd=magic")

%>

<P>

<Input type="submit" value="Get Data">&nbsp;<Input type="reset" value="Clear


City"></form>

</BODY></HTML>

<!--#include virtual="/learn/test/lib_dblistm.asp"-->

The responder looks like this:

<HEAD><TITLE>sqlcitiesrespond.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

citycount=request.form("cy").count

If citycount=0 then%>

<B>You never choose a city!</b><br>

<a href="sqlcities.asp">Choose City</a>

<%

response.end

end if

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 126 de 142
firstcity=request.form("cy")(1)

SQLtemp="select * from publishers "

SQLtemp = SQLtemp & " where city='" & firstcity & "'"

for counter=2 to citycount

whichcity=request.form("cy")(counter)

SQLtemp = SQLtemp & " or city='" & whichcity & "' "

next

response.write SQLtemp

call query2table(SQLtemp,"DSN=student;uid=student;pwd=magic")

%>

<!--#include virtual="/learn/test/lib_dbtable.asp"-->

</BODY></HTML>

The file lib_dbtable.asp looks like this:

<%

sub query2table(inputquery, inputDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open inputDSN

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 127 de 142
thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

The file lib_dblistm.asp looks like this:

<%

SUB query2listm(myquery,myname,myDSN)

dim conntemp, rstemp

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

set rstemp=conntemp.execute(myquery)

%>

<Select name="<%=myname%>" multiple>

<%

do while not rstemp.eof

thisfield=trim(RStemp(0))

if isnull(thisfield) or thisfield="" then

' ignore

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 128 de 142
else

response.write "<option>" & thisfield & "</option>"

end if

rstemp.movenext

loop

%>

</select>

<%rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

END SUB

%>

SQL Count Syntax/Examples


SQL can count items. There are a few variations on the syntax and some simple rules to remember:

 Any field you want to count here is the simplest syntax

 "select count(*) from publishers where state='NY'

 If you count a specific field you must groupby that field or it won't work:

 "select count(city),city from publishers group by city"

 The AS operator allows you to specify a name for the counted field:

 "select count(city) as howmany,city from publishers group by city"

Test the Script --> /learn/test/sqlcount1.asp

<HEAD><TITLE>SQLcount1.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select count(*) from publishers where state='NY'")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 129 de 142
Test the Script --> /learn/test/sqlcount2.asp

<HEAD><TITLE>SQLcount2.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select count(city),city from publishers group by city")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

Test the Script --> /learn/test/sqlcount3.asp

<HEAD><TITLE>SQLcount3.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select count(city) as howmany,city from publishers group by


city")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

Test the Script --> /learn/test/sqlcount4.asp

<HEAD><TITLE>SQLcount4.asp</TITLE></HEAD>

<HTML><body bgcolor="#FFFFFF">

<%

call query2table("select count(*),city,state from publishers group by


city,state")

%>

<!--#include virtual="/learn/test/subdbtable.inc"-->

</BODY></HTML>

The Include file looks like this:

<%

sub query2table(inputquery)

set conntemp=server.createobject("adodb.connection")

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 130 de 142
conntemp.open "DSN=Student;uid=student;pwd=magic"

set rstemp=conntemp.execute(inputquery)

howmanyfields=rstemp.fields.count -1%>

<table border=1><tr>

<% 'Put Headings On The Table of Field Names

for i=0 to howmanyfields %>

<td><b><%=rstemp(i).name%></B></TD>

<% next %>

</tr>

<% ' Now lets grab all the records

do while not rstemp.eof %>

<tr>

<% for i = 0 to howmanyfields

thisvalue=rstemp(i)

If isnull(thisvalue) then

thisvalue="&nbsp;"

end if%>

<td valign=top><%=thisvalue%></td>

<% next %>

</tr>

<%rstemp.movenext

loop%>

</table>

<%

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

end sub%>

Database -- Inner Joins by Aaron Alexander

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 131 de 142
In this demonstration I will explain to you how joins between tables work in SQL. I will use the verbose SQL rather
than the shortcuts due to the fact that the shortcuts differ between databases.

I would first like to define some terms that I will be using:

Primary Key(PK): This is the unique field in your table that is used to identify each record. (Ex: RecID)

Foreign Key(FK): This is a column that references a primary key of another table. It can have duplicate values.

We have 2 tables defined:

Customer

CustomerID(PK) CustomerName

1 Joe Schmoe

2 Fred Flintstone

Sales

ID(PK) CustomerID(FK) SalesAmount

3 1 $1.00

4 1 $22.00

5 1 $3.00

6 20 $22.00

Inner Joins

When joining two tables there are two ways to do it. The most common way is the inner join.

The inner join will return all data where all joined data exists.

Lets look at this example of an inner-join:

SELECT Customer.CustomerName, Sales.SalesAmount FROM Customer INNER JOIN Sales ON


customer.CustomerID = Sales.CustomerID

In our example above, we are selecting all the Customer Names and amount of the sale where the customer numbers
exist in both tables. The result of the query is this:

CustomerName SalesAmount

Joe Schmoe $1.00

Joe Schmoe $22.00

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 132 de 142
Joe Schmoe $3.00

Note that record ID 6 in the sales table with customer ID of 20 is not in our result. Since that joined data does not
exist we do not see the data.

Note: The SQL above can be written a lot simpler, doing it this way will avoid confusion when other tables are
added:

SELECT Customer.CustomerName, Sales.SalesAmount FROM Customer , Sales where


customer.CustomerID = Sales.CustomerID

Outer Joins

The outer join is useful when we want to return all data from one table, and also return linked data from another,
when it exists, but here is where we differ from the inner join, we want to return all data from table 1 no matter
what.

In our example we want to return all sales, even if there isn’t a valid customer associated with it.

Here is what our SQL will look like:

SELECT Customer.CustomerName, Sales.SalesAmount FROM Customer RIGHT JOIN Sales ON


Customer.CustomerID = Sales.CustomerID

Our results will look like this:

CustomerName SalesAmount

Joe Schmoe $1.00

Joe Schmoe $22.00

Joe Schmoe $3.00

$22.00

Notice we did a right join. We chose to select all the data from the right table in our join statement. What would it
look like if we changed to this:

SELECT Customer.CustomerName, Sales.SalesAmount FROM Customer LEFT JOIN Sales ON


Customer.CustomerID = Sales.CustomerID;

Our results:

CustomerName SalesAmount

Joe Schmoe $1.00

Joe Schmoe $22.00

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 133 de 142
Joe Schmoe $3.00

Fred Flintstone

The results gave us all the records from the left table (Customer) and the linked data from the right.

As with the inner join there are shortcuts for joins, but that depends on which database you are using. Writing the
verbose SQL statement will work on all databases.

I hope this helps clear things up.

Aaron Alexander

Browser Capabilites
The script below demonstrates the most commonly used property of the Browser Capabilites
component.

Test the Script --> /learn/test/bc.asp

<html><head>

<TITLE>bc.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<% Set bc = Server.CreateObject("MSWC.BrowserType") %>

Browser Name: <%=bc.browser %><p>

Browser Version: <%=bc.version%><p>

<% if (bc.frames = TRUE) then %>

I noticed you do frames<p>

<% else %>

I noticed you are frame challenged<p>

<% end if %>

<% if (bc.tables = TRUE) then %>

I noticed you do tables<p>

<% else %>

I noticed you can't do tables<p>

<% end if %>

<% if (bc.BackgroundSounds = TRUE)then %>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 134 de 142
I noticed you allow me to play music<p>

<% else %>

I noticed you aren't a music listener<p>

<% end if %>

<% if (bc.vbscript = TRUE) then %>

I noticed you are VBscript capable<p>

<% else %>

I noticed you can't understand VB Script<p>

<% end if %>

<% if (bc.javascript = TRUE) then %>

I noticed you understand JScript<p>

<% else %>

I noticed you don't understand JScript<p>

<%

end if

set bc=nothing

%>

</body></html>

Do Loop Intercept Timeouts by Charles Carroll


The transactional nature of ASP pages can be used to intercept a script timeout.
loop3.asp traps a timeout:

Test the Script --> /learn/test/loop3.asp

<%@ TRANSACTION=Required%>

<%

response.buffer=true

server.scripttimeout=20

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 135 de 142
%>

<HTML>

<TITLE>loop3.asp</TITLE>

<body bgcolor="#FFFFFF">

</BODY>

<%

DO

counter=counter+1

response.write counter & "<br>"

LOOP

response.flush

response.write "Script executed without incident"

%>

</HTML>

<%

Sub OnTransactionAbort()

response.clear

Response.Write "The Script Timed Out"

end sub

%>

loop4.asp succeeds and does not trigger the trap:


Test the Script --> /learn/test/loop4.asp

<%@ TRANSACTION=Required%>

<%

response.buffer=true

server.scripttimeout=40

%>

<HTML>

<TITLE>loop4.asp</TITLE>

<body bgcolor="#FFFFFF">

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 136 de 142
</BODY>

<%

DO UNTIL counter=400

counter=counter+1

response.write counter & "<br>"

LOOP

response.flush

response.write "Script Exexuted without incident!"

%>

</HTML>

<%

Sub OnTransactionAbort()

response.clear

Response.Write "The Script Timed Out"

end sub

%>

Do Loop and Timeouts by Charles Carroll


A loop that is infinite will not run forever. IIS will timeout the script (default is 90 seconds).
Here is an infinite loop that IIS will timeout:
Test the Script --> /learn/test/loop1.asp

<%response.buffer=true%>

<TITLE>doloop1.asp</TITLE>

<body bgcolor="#FFFFFF">

<HTML>

<%

DO

counter=counter+1

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 137 de 142
response.write counter & "<br>"

response.flush

LOOP

%>

</BODY>

</HTML>

Here is an infinite loop that we explicitly set a timeout for:


Test the Script --> /learn/test/loop2.asp

<%

response.buffer=true

server.scripttimeout=20

%>

<TITLE>loop2.asp</TITLE>

<body bgcolor="#FFFFFF">

<HTML>

<%

DO

counter=counter+1

response.write counter & "<br>"

response.flush

LOOP

%>

</BODY>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 138 de 142
</HTML>

It has been assumed that a timed out script was impossible to intercept, but the next lesson shows
how to use the transactional aspect of an ASP script to capture this elusive condition.

What are Sessions?


Sessions are a very convenient ASP feature. When someone visits a web page on your site, ASP calls
that a "session" and immediately can differentiate that user from all other users at a site. Anything stored
in that user's session can be retrieved and manipulated from that page and the next pages they visit,
and the data will be tied to that user.

Session data is generally attached to one user. When a user visits their first page of your site, that page
and every page they visit is collectively called a session. Any data attached stored in that session object is
private to the pages that user is visiting.

The code to store data in a session variable is simple. Here we will allow a user to flip a coin, i.e.
flipcoin.asp and count their successes:

Test the Script --> /learn/test/flipcoin.asp

<%

response.write "Coin Tossed!<br>"

randomize

randomnum=int(rnd*2)+1

IF randomnum=1 THEN

session("heads")=session("heads")+1

ELSE

session("tails")=session("tails")+1

END IF

response.write "Heads= " & session("heads") & "<br>"

response.write "Tails= " & session("tails") & "<br>"

%>

Even though there are many people at the site they all have different scores for their "heads" and "tails"
count. They each has a session and it co-ordinates and differentiates their values.

A much more practical example could protect access to a page based on a session variable that indicated
their security level determined once upon login, see:

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 139 de 142
http://www.learnasp.com/learn/security.asp

Some basic things should be noted:

 Session data is stored on the server, not in cookies. No user could examine the
session cookie and determine the contents of any session variables.

 A cookie is used to co-ordinate the user's session ID. Once again the cookie
contains no data (just the session ID). This means if the user accepts no cookies,
you can't use sessions as described here.

 If you absolutely need sessions without client cookies, installing an ISAPI filter
named "Cookie Munger" will solve your problem, but at a performance penalty.

Cookie Munger by Microsoft (FREE)

Cookies are a necessity to maintain ASP session objects. Even though the session objects are physically
maintained on the server the essential ID that identifies a user session is kept in a cookie. This ISAPI filter
can only be applied globally but if applied, it actually rewrites any pages sent back to the user so that any
URLs in the page will pass back user session info without any cookies involved. Basically (at a
performance penalty) it transforms every page sent to the client to encode the session ID as part of the
URLs on the page. So conceptually if you send a page back to the users with 20 URLs each URL gets a
session ID "munged"/intermixed in so that when they click on the URL you have enough info to Identify
them without writing a cookie to their machine.

Include Files Dynamically by Charles Carroll


The include files are gathered and processed BEFORE any ASP code. Soif your code looks like this:

<%SELECT CASE

CASE 1 %>

    <!­­#include virtual="whatever1.asp"­­>
CASE 2 %>

    <!­­#include virtual="whatever2.asp"­­>
CASE 3 %>

    <!­­#include virtual="whatever3.asp"­­>

<%END SELECT%>
Three includes are performed before any ASP code is executed.

YOU CANNOT DO:

<%

whichfile="1"%>

  <!­­#include virtual="whatever<%=whichfil%>.asp"­­>
Though this is a reasonable idea.

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 140 de 142
<!­­#include virtual="whatever.asp"­­>
The alternative is:

Test the Script --> /learn/test/includedynamic.asp

<html><head>

<TITLE>includedynamic.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<%

whichfile="bookscifi.asp"

Call ReadDisplayFile(whichfile)

response.write "<hr>"

whichfile="bookhorror.asp"

Call ReadDisplayFile(whichfile)

response.write "<hr>"

whichfile="/learn/test/bookmarketing.asp"

Call ReadDisplayFile(whichfile)

response.write "<hr>"

%>

</body></html>

<%

SUB ReadDisplayFile(FileToRead)

whichfile=server.mappath(FileToRead)

Set fs = CreateObject("Scripting.FileSystemObject")

Set thisfile = fs.OpenTextFile(whichfile, 1, False)

tempSTR=thisfile.readall

response.write tempSTR

thisfile.Close

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 141 de 142
set thisfile=nothing

set fs=nothing

END SUB

%>

The only downside to this method is no ASP Code ( i.e. anything in <% %> ) will be parsed or executed in
the included file.

HTML List Box from Column


This page demonstrates the capabilities how to display a list box from a SQL statement. This is the
simplest possible example. The script to display a list from a database is:

Test the Script --> /learn/test/dblist.asp

<html><head>

<TITLE>dblist.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<%

myDSN="DSN=Student;uid=student;pwd=magic"

mySQL="select author from authors where AU_ID<100"

' displays a database field as a listbox

set conntemp=server.createobject("adodb.connection")

conntemp.open myDSN

set rstemp=conntemp.execute(mySQL)

if rstemp.eof then

response.write "no data for<br>"

response.write mySQL

conntemp.close

set conntemp=nothing

response.end

end if

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa
http://www.learnasp.com/learn/dbtablelists.asp Página 142 de 142
%>

<form action="dblistrespond.asp" method="post">

<Select name="authorname">

<%

' Now lets grab all the data

do until rstemp.eof %>

<option> <%=RStemp(0)%> </option>

<%

rstemp.movenext

loop

rstemp.close

set rstemp=nothing

conntemp.close

set conntemp=nothing

%>

<input type="submit" value="Choose Author">

</Select></form>

</body></html>

The form responder dblistrespond.asp is:

<html><head>

<TITLE>dblistrespond.asp</TITLE>

</head><body bgcolor="#FFFFFF">

<%

my_author=request.form("authorname")

%>

You choose <%=my_author%><br>Thanks!<br>

</body></html>

FMwww.flavioaraujo.cjb.net ou www10.ewebcity.com/flavioaraujo/fa

Das könnte Ihnen auch gefallen