Active Server Pages
Active Server Pages
Active Server Pages (ASPs) are Web pages that contain server-side
scripts in addition to the usual mixture of text and HTML (Hypertext Markup
Language) tags. Server-side scripts are special commands you put in Web
pages that are processed before the pages are sent from your Personal Web
Server to the Web browser of someone who's visiting your Web site. . When
you type a URL in the Address box or click a link on a Web page, you're asking
a Web hosting server on a computer somewhere to send a file to the Web
browser (sometimes called a "client") on your computer. If that file is a
normal HTML file, it looks exactly the same when your Web browser receives
it as it did before the Web server sent it. After receiving the file, your Web
browser displays its contents as a combination of text, images, and sounds.
To distinguish them from normal HTML pages, Active Server Pages are
given the ".asp" extension.
1
What is an ASP File?
ASP Files
ASP files can be ordinary HTML files. In addition, ASP files can also
contain server scripts.
Scripts surrounded by <% and %> are executed on the server.
The Response.Write() method is used by ASP to write output to HTML.
<!DOCTYPE html>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>
VBScript is case insensitive. Response.Write() can be written as
response.write().
2
Using JavaScript in ASP
To set JavaScript as the scripting language for a web page you must insert a
language specification at the top of the page:
<%@ language="javascript"%>
<!DOCTYPE html>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>
There is an easy shortcut to Response.Write(). You can use an equal sign (=)
instead.
<!DOCTYPE html>
<html>
<body>
<%
="Hello World!"
%>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<%
Response.Write("<p style='color:#0000ff'>This text is styled.</p>")
%>
</body>
</html>
What Do Server-Side Scripts Look Like?
Server-side scripts look a lot like HTML tags. However, instead of starting and
ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically
start with <% and end with %>. The <% is called an opening tag, and the %> is
called a closing tag. In between these tags are the server-side scripts. You can
insert server-side scripts anywhere in your Web page--even inside HTML tags.
3
How ASP works? The below is the process:
1. The Web browser sends a request to your web server asking for a page.
2. The Web server loads the page and looks for ASP code to run.
3. If ASP code is found, the web server runs the code and sends the results
to the Web browser. So the result page on the client side looks like a
pure HTML page.
You may wonder why we need an ASP page to display web contents while we
have HTML. Well, HTML can be used to display web contents, but the page is
static, not dynamic. Image you have a website that sells products, and you
want to display the name, price, description and category of each product on a
page. Normally in HTML you would have to write this page out by hand, and
every time you change products or prices you would have to go back and re-
write the page. But if you use ASP, you can select records from a database and
generate the HTML page when an user requests it. When you get a new
product or change the prices you will only have to change the information in
the database and the page will automatically be updated to reflect those
changes without writing a single line of code.
ASP Code
When writing ASP you don't need to worry about changing all your HTML, you
simply add ASP code into your HTML pages where needed. YOu also don't
need any special software on your computer, a simple text editor will do. To
begin an ASP page you will first need to tell it what language you have written
it in. The most common (and the one used in this tutorial) is VBScript. You
should begin your page with:
All this code does is tell the ASP system that you are writing your page in
VBScript. You will notice that the ASP code is enclosed in special tags. All ASP
code should be enclosed in the 'percent sign tags' in the form:
4
Code can be written over multiple lines, but any code not enclosed in the ASP
tags will simply be treated as HTML. Similarly and HTML inside these tags but
not specifically sent as output by the code will cause an error.
Response.Write()
so to write 'Hello World' to the user's browser the complete code would be:
<%@ Language=VBScript %>
Again, this code begins by telling the system that you are writing in VBScript.
Then comes the Response.Write command. Basically this is made up of two
parts. 'Response' tells the server that you want to send information to the
user. There are other types of command including: Request (which gets
information from the user), Session (for user session details), Server (for
controlling the server) and Application (for commands relating to the
application). More about these later.
The second part, 'Write', tells the server that the type of response you would
like to send is to write information to the user's browser. This doesn't just
have to be text, but can include variables, which will be discussed in more
depth later in this tutorial.
Variables
Probably the most important feature of a programming language is a variable.
A variable is basically a way of storing text, numbers or other data, so that it
can be referenced later. For example, to change the earlier 'Hello World'
script:
5
This line sets up a variable called OutputText and stores in it the string of
letters 'Hello World'.
As this is now stored in a variable, you can now reference this text you have
stored in any part of your script, and you can also manipulate it. The next line:
Response.Write(OutputText)
tells the server that you are sending information to the browser, and that the
information to be sent is the contents of the variable called OutputText. Please
note that the variable name is not enclosed in quotation marks. If you did this
the browse would simply output the title of the variable as text.
There is a second way of outputting the values of variables, other than using
Response.Write. The earlier code could have been written:
The main benefits to storing information in variables is that you can use the
text over and over again. For example, once storing "Hello World" in the
variable OutputText, I can then use it in various places in my code:
This is my <% =OutputText %> script. The whole reason for it is to output the
text <% =OutputText %> to the browser.
This is my Hello World script. The whole reason for it is to output the text
Hello World to the browser.
6
Variables
Now you have created two variables. The name of the variables are "x"
and "carname".
You can also declare variables by using its name in a script. Like this:
carname="Volvo"
The scope of a variable refers to its accessibility by the application (ASP site).
How you can access a variable depends on where you declare it in the
application:
7
A session variable is accessible by all pages in a site but applies only to a
single client (user). In ASP, sessions are created when a user enters a site
and destroyed when the user fails to access a page on a site in a specified
period of time. Session variables typically store information about that
user.
An application variable is accessible by all pages in a site and can be used
by all clients accessing the site.
You can also do various operations on text stored in variables using len, left
and right.
The len function simply tells you how many characters are in a string, so if you
used the following code:
The server would return to the browser the length of the text stored in
OutputText, in this case "Hello World", so the browser would display the
number 11 on the screen. You could also ssign this value to a variable using:
which would set the value of the variable called StringLength to 11.
You can also use the functions left and right. These will display only part of the
variable. For example:
He
and the code:
would display:
orld
Basically, these functions take the number of characters specififed from the
left or right of the string, so left("Some Text", 5) takes the first 5 characters of
the text.
8
Must begin with a letter
Cannot contain a period (.)
Cannot exceed 255 characters
In VBScript, all variables are of type variant, that can store different types of
data.
you can use the Option Explicit statement. This statement forces you to
declare all your variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:
Option Explicit
Dim carname
carname=some value
carname="Volvo"
x=10
The variable name is on the left side of the expression and the value you want
to assign to the variable is on the right. Now the variable "carname" has the
value of "Volvo", and the variable "x" has the value of "10".
Session Variables
Session variables are used to store information about ONE single user, and are
available to all pages in one application. Typically information stored in
session variables are name, id, and preferences.
9
Application Variables
VARIABLES:
For a regular variable, you simply assign a value to it. You don't have to
predefine it - it knows by what type of variable you're assigning to it what sort
of a variable it is. So if you say:
SiteName = "ASP"
it knows it's a text variable that you can do text operations on. If you say
BooksOrdered = 13
then it knows it's a numeric variable and that you can do addition and
10
subtraction to it.
The date subtype needs a special format so that the system doesn't think it's
just a string or a division problem :). You use # signs to indicate it's a date, as
in:
DateStarted = #01/15/2001#
Also, if you want to use booleans (true/false), you simply use TRUE or FALSE
as your values. So:
FinishedTask = TRUE
Constant variables
ASP Code:
<%
Dim myFixedArray(3) 'Fixed size array
Dim myDynArray() 'Dynamic size array
%>
We are going to focus on fixed size arrays first and cover dynamic arrays later
on in this lesson.
Let's fill up our fixed size array with values. Our fixed array is going to store
the names of famous people. To assign a value to an array you need to know
three things:
11
An array is a group of variables that you can access by specifying
the positioninside the array. Our array myFixedArray has four positions: 0, 1, 2
and 3. Let's assign some values to our array.
ASP Code:
<%
Dim myFixedArray(3) 'Fixed size array
myFixedArray(0) = "Albert Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Martin Luther King Jr."
%>
asp arrays are zero based!
you only allocated three elements for that array, but you assigned four values!
Well, this can be done because arrays in ASP are zero based. This means when
you declare fixed array of size X then you can assign values for each value
from 0 through X.
Below is perfectly functional ASP code that will go through our array and print
out the contents of each element. Don't worry if you are confused by this
new for loop code it will be taught later.
ASP Code:
<%
Dim myFixedArray(3) 'Fixed size array
myFixedArray(0) = "Albert Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Martin Luther King Jr."
For Each item In myFixedArray
Response.Write(item & "<br />")
Next
%>
12
Display:
Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.
To create an array whose size can be changed at any time simply do not put a
number within the parenthesis when you declare the array. When you know
what size you want the array to be use the ReDim keyword. You may ReDim as
many times as you wish.
If you want to keep your data that already exists in the array then use
the Preserve keyword. Below is an example of all these things we have just
talked about.
ASP Code:
<%
Dim myDynArray() 'Dynamic size array
ReDim myDynArray(1)
myDynArray(0) = "Albert Einstein"
myDynArray(1) = "Mother Teresa"
ReDim Preserve myDynArray(3)
myDynArray(2) = "Bill Gates"
myDynArray(3) = "Martin Luther King Jr."
For Each item In myDynArray
Response.Write(item & "<br />")
Next
%>
Display:
Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.
Arrays do not have to be a simple list of keys and values; each location in the
array can hold another array. This way, you can create a multi-dimensional
array. The reason you may use this type of array is when you have records of
13
each item. For example, car, year, price,... and you want display one record at
a time.
The most commonly used are two-dimensional arrays. You can think of a two-
dimensional array as a matrix, or grid, with width and height or rows and
columns. Here is how you could define two-dimensional array and display the
array values on the web page:
Example:
14
Response.Write("<TR><TD>#" & i & "</TD>")
Response.Write("<TD>" & arrCars(0,i) & "</TD>")
Response.Write("<TD>" & arrCars(1,i) & "</TD>")
Response.Write("<TD>" & arrCars(2,i) & "</TD></TR>")
Next
Response.Write("</TABLE>")
%>
15
statement_n
end sub
%>
A function differs from a subroutine in the fact that it returns data, start with
Function keyword and end with End Function. Functions are especially good
for doing calculations and returning a value. To declare a function, the syntax
is similar:
Have a look at the code for a procedure that is used to print out information on
the page:
Now let's consider how to call the sub. There are two ways:
<%
'the first method
Call GetInfo("Mr. O'Donnel","555-5555",20)
'the second one
GetInfo "Mr. O'Donnel","555-5555",20 %>
16
In each example, the actual argument passed into the subprocedure is passed
in the corresponding position. Note that if you use the Call statement, the
arguments must be enclosed in parentheses. If you do not use call, the
parentheses aren't used.
Now let's look at the code for a function that takes an integer value and
returns the square of that value. Also included is code to call the function.
<%
Function Square(num)
Square = num * num
end function
'Returns 25
Response.Write(Square(5))
To return a value from a function, you need to name the output value the same
as your function or you will not get a value returned.
Code Comments
In the programming world, a comment is text that the compiler would not
consider when reading the code. As such a comment can be written any way you
want. In VBScript, the line that contains a comment can start with a single quote.
Here is an example:
Alternatively, you can start a comment with the Rem keyword. Anything on the
right side of rem, Rem, or REM would not be read. Here is an example:
17
Comments are very useful and you are strongly suggested to use them regularly.
They can never hurt your code and they don't increase the size of your
application. Comments can help you and other people who read your code to
figure out what a particular section of code is used for, which can be helpful
when you re-visit your code after months or years of not seeing it.
Line Continuation: _
You will regularly need to expand your code on more than one line. This
happens if you are writing an expression that involves many entities that must
belong to a group.
Before a database can be accessed from a web page, a database connection has
to be established.
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
%>
Note, from the example above, that you have to specify the Microsoft Access
database driver (Provider) and the physical path to the database on your
computer.
18
Create an ODBC Database Connection
If you have an ODBC database called "northwind" you can connect to the
database with the following ASP code:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Open "northwind"
%>
With an ODBC connection, you can connect to any database, on any computer
in your network, as long as an ODBC connection is available.
Note that this configuration has to be done on the computer where your web
site is located. If you are running Personal Web Server (PWS) or Internet
Information Server (IIS) on your own computer, the instructions above will
work, but if your web site is located on a remote server, you have to have
physical access to that server, or ask your web host to do this for you.
Connection Object
19
If you want to access a database multiple times, you should establish a
connection using the Connection object. You can also make a connection to a
database by passing a connection string via a Command or Recordset object.
However, this type of connection is only good for one specific, single query.
ProgID
set objConnection=Server.CreateObject("ADODB.connection")
Properties
Property Description
Attributes Sets or returns the attributes of a Connection
object
CommandTimeout Sets or returns the number of seconds to wait
while attempting to execute a command
ConnectionString Sets or returns the details used to create a
connection to a data source
ConnectionTimeout Sets or returns the number of seconds to wait
for a connection to open
CursorLocation Sets or returns the location of the cursor
service
DefaultDatabase Sets or returns the default database name
IsolationLevel Sets or returns the isolation level
Mode Sets or returns the provider access permission
Provider Sets or returns the provider name
State Returns a value describing if the connection is
open or closed
Version Returns the ADO version number
Methods
Method Description
BeginTrans Begins a new transaction
Cancel Cancels an execution
Close Closes a connection
CommitTrans Saves any changes and ends the current
20
transaction
Execute Executes a query, statement, procedure or
provider specific text
Open Opens a connection
OpenSchema Returns schema information from the provider
about the data source
RollbackTrans Cancels any changes in the current transaction
and ends the transaction
Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
Event Description
BeginTransComplete Triggered after the BeginTrans
operation
CommitTransComplete Triggered after the CommitTrans
operation
ConnectComplete Triggered after a connection
starts
Disconnect Triggered after a connection
ends
ExecuteComplete Triggered after a command has
finished executing
InfoMessage Triggered if a warning occurs
during a ConnectionEvent
operation
RollbackTransComplete Triggered after the
RollbackTrans operation
WillConnect Triggered before a connection
starts
WillExecute Triggered before a command is
executed
21
Collections
Collection Description
Errors Contains all the Error objects of the Connection
object
Properties Contains all the Property objects of the Connection
object
To be able to read database data, the data must first be loaded into a
recordset.
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Customers", conn
%>
We can also get access to the data in the "Customers" table using SQL:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
%>
22
Extract Data from the Recordset
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
The ADO Recordset object is used to hold a set of records from a database
table.
Examples
GetRows
This example demonstrates how to use the GetRows method.
Recordset Object
The ADO Recordset object is used to hold a set of records from a database
table. A Recordset object consist of records and columns (fields).
In ADO, this object is the most important and the one used most often to
manipulate data from a database.
23
ProgID
set objRecordset=Server.CreateObject("ADODB.recordset")
When you first open a Recordset, the current record pointer will point to the
first record and the BOF and EOF properties are False. If there are no records,
the BOF and EOF property are True.
The cursor type can be set by the CursorType property or by the CursorType
parameter in the Open method.
Note: Not all providers support all methods or properties of the Recordset
object.
24
Properties
Property Description
DataMember Sets or returns the name of the data member that will be
retrieved from the object referenced by the DataSource
property
EOF Returns true if the current record position is after the last
25
record, otherwise false
26
Methods
Method Description
27
Resync Refreshes the data in the current Recordset from
the original database
Save Saves a Recordset object to a file or a Stream object
Seek Searches the index of a Recordset to find a record
that matches the specified values
Supports Returns a boolean value that defines whether or not
a Recordset object supports a specific type of
functionality
Update Saves all changes made to a single record in a
Recordset object
UpdateBatch Saves all changes in a Recordset to the database.
Used when working in batch update mode
Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
Description
28
RecordsetChangeComplete Triggered after the Recordset has changed
Collections
Collection Description
Property Description
Example:
countfields=rs.Fields.Count
Item(named_item/number) Returns a specified item in the fields collection.
Example:
itemfields=rs.Fields.Item(1)
or
itemfields=rs.Fields.Item("Name")
29
The Properties Collection's Properties
Property Description
Example:
countprop=rs.Properties.Count
Item(named_item/number) Returns a specified item in the properties
collection.
Example:
itemprop = rs.Properties.Item(1)
or
itemprop=rs.Properties.Item("Name")
ADO Display
The most common way to display data from a recordset, is to display the data
in an HTML table.
We have a database named "Northwind" and we want to display the data from
the "Customers" table (remember to save the file with an .asp extension):
Example
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT * FROM Customers", conn
do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br>")
30
next
Response.Write("<br>")
rs.MoveNext
loop
rs.close
conn.close
%>
</body>
</html>
We can also display the data from the "Customers" table inside an HTML table
with the following lines (remember to save the file with an .asp extension):
Example
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT Companyname, Contactname FROM Customers", conn
%>
</body>
</html>
31
Add Headers to the HTML Table
Example
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM Customers"
rs.Open sql, conn
%>
</body>
</html>
32
ADO Queries
We want to display only the records from the "Customers" table that have a
"Companyname" that starts with an A (remember to save the file with an .asp
extension):
<html> <body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM Customers
WHERE CompanyName LIKE 'A%'"
rs.Open sql, conn
%>
<table border="1" width="100%">
<tr>
<%for each x in rs.Fields
response.write("<th>" & x.name & "</th>")
next%>
</tr>
<%do until rs.EOF%>
<tr>
<%for each x in rs.Fields%>
<td><%Response.Write(x.value)%></td>
<%next
rs.MoveNext%>
</tr>
<%loop
rs.close
conn.close%>
</table>
</body>
</html>
33
Let the user choose filter
Let the user choose which country to show customers from.
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
sql="SELECT DISTINCT Country FROM Customers ORDER BY Country"
rs.Open sql,conn
country=request.form("country")
%>
<form method="post">
Choose Country <select name="country">
<% do until rs.EOF
response.write("<option")
if rs.fields("country")=country then
response.write(" selected")
end if
response.write(">")
response.write(rs.fields("Country"))
rs.MoveNext
loop
rs.Close
set rs=Nothing %>
</select>
<input type="submit" value="Show customers">
</form>
34
<%
if country<>"" then
sql="SELECT Companyname,Contactname,Country FROM Customers
WHERE country='" & country & "'"
set rs=Server.CreateObject("ADODB.Recordset")
rs.Open sql,conn
%>
<table width="100%" cellspacing="0" cellpadding="2" border="1">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Country</th>
</tr>
<%
do until rs.EOF
response.write("<tr>")
response.write("<td>" & rs.fields("companyname") & "</td>")
response.write("<td>" & rs.fields("contactname") & "</td>")
response.write("<td>" & rs.fields("country") & "</td>")
response.write("</tr>")
rs.MoveNext
loop
rs.close
conn.Close
set rs=Nothing
set conn=Nothing%>
</table>
<% end if %>
</body>
</html>
35
ADO Sort
Example
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM
Customers ORDER BY CompanyName"
rs.Open sql, conn
%>
</body>
</html>
36
ADO Add Records
We may use the SQL INSERT INTO command to add a record to a table in a
database.
<html>
<body>
</body>
</html>
37
When the user presses the submit button the form is sent to a file called
"demo_add.asp". The "demo_add.asp" file contains the code that will add a
new record to the Customers table:
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
</body>
</html>
Important
If the table contains a primary key, make sure to append a unique, non-
Null value to the primary key field (if not, the provider may not append
the record, or an error occurs)
If the table contains an AutoNumber field, do not include this field in the
SQL INSERT command (the value of this field will be taken care of
automatically by the provider)
38
ADO Update Records
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>
<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_update.asp">
<%
for each x in rs.Fields
if lcase(x.name)="customerid" then%>
<td>
<input type="submit" name="customerID" value="<%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
39
</table>
</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be
taken to a new file called "demo_update.asp". The "demo_update.asp" file
contains the source code on how to create input fields based on the fields from
one record in the database table. It also contains a "Update record" button
that will save your changes:
<html>
<body>
<h2>Update Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID")
if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
%>
<form method="post" action="demo_update.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br><br>
<input type="submit" value="Update record">
</form>
40
<%
else
sql="UPDATE customers SET "
sql=sql & "companyname='" & Request.Form("companyname") & "',"
sql=sql & "contactname='" & Request.Form("contactname") & "',"
sql=sql & "address='" & Request.Form("address") & "',"
sql=sql & "city='" & Request.Form("city") & "',"
sql=sql & "postalcode='" & Request.Form("postalcode") & "',"
sql=sql & "country='" & Request.Form("country") & "'"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was updated!")
end if
end if
conn.close
%> </body> </html>
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>
<h2>List Database</h2>
41
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_delete.asp">
<%
for each x in rs.Fields
if x.name="customerID" then%>
<td>
<input type="submit" name="customerID" value="<%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>
</body>
</html>
42
ADO Delete Records
If the user clicks on the button in the "customerID" column he or she will be
taken to a new file called "demo_delete.asp". The "demo_delete.asp" file
contains the source code on how to create input fields based on the fields from
one record in the database table. It also contains a "Delete record" button that
will delete the current record:
<html>
<body>
<h2>Delete Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
cid=Request.Form("customerID")
if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
%>
<form method="post" action="demo_delete.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br><br>
<input type="submit" value="Delete record">
</form>
<%
else
43
sql="DELETE FROM customers"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was deleted!")
end if
end if
conn.close
%>
</body>
</html>
ADO Demonstration
If you try to update the database, you will get the error message: "You do not
have permission to update this database". You get this error because you don't
have write access to our server.
BUT, if you copy the code and run it on your own system, you might get the
same error. That is because the system might see you as an anonymous
internet user when you access the file via your browser. In that case, you have
to change the access-rights to get access to the file.
Open Windows Explorer, find the .mdb file. Right-click on the .mdb file and
select Properties. Go to the Security tab and set the access-rights here.
44