Anda di halaman 1dari 89

Active

Server Pages
(ASP)

Active Server Pages (ASP)is an server-side


technology that dynamically builds documents
(e.g., XHTML, text, XML) in response to client
requests.
An ASP file has the file extension .asp and
contains XHTML tags and scripting code.
Although other languages, like JavaScript, can
be used for ASP scripting, VBScript
An ASP file can contain text, HTML tags and
scripts. Scripts in an ASP file are executed on
the server
Active Server Pages technology is the precursor
technology to ASP.NET

What Are 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 Web Server to the Web browser of
someone who's visiting your Web site.
Before the Web server sends the Active Server Page to
the Web browser, it runs all server-side scripts
contained in the page. Some of these scripts display
the current date, time, and other information. Others
process information the user has just typed into a
form, such as a page in the Web site's guestbook

How Active Server Pages Work


Active Server Pages are processed by an
ActiveX component (i.e., a serverside ActiveX
control) called a scripting engine. An
ASP file has the file extension .asp
and contains
XHTML tags and scripting code. Although
other languages, like JavaScript, can be
used for ASP scripting, VBScript is the
most widely used.

ASP is a Microsoft technology for sending the client


dynamic Web content, including XHTML, Dynamic
HTML, ActiveX controls, client-side scripts and Java
applets (i.e., client-side)
The Active Server Page processes the request
(which often includes interacting with a database)
and returns the results to the clientnormally in the
form of an XHTML document, but other data formats
(e.g., images, binary data) can be returned.
When a client requests an ASP document, it is
loaded into memory and parsed (top to bottom) by a
scripting engine named asp.dll. Script code is
interpreted as it is encountered.

Uses of ASP

There are many things you can do with Active Server Pages .
You can display date, time, and other information in different
ways.
You can make a survey form and ask people who visit your site
to fill it out, send emails, save the information to a file, etc
Dynamically edit, change, or add any content of a Web page
Respond to user queries or data submitted from HTML forms
Access any data or databases and return the results to a browser
Customize a Web page to make it more useful for individual
users
The advantages of using ASP instead of CGI and Perl, are those
of simplicity and speed
Provide security - since ASP code cannot be viewed from the
browser
Clever ASP programming can minimize the network traffic

What you should already know!

Before you continue you should have


some basic understanding of the
following:
HTML / XHTML
A scripting language like JavaScript or
VBScript

Run ASP onYour Own PC

Since the server must do additional


processing on the ASP scripts, it must
have the ability to do so. The only
servers which support this facility are
Microsoft Internet Information Services
& Microsoft Personal Web Server

Your Windows PC as a Web Server

Your own PC can act as a web server if


you install IIS or PWS
IIS or PWS turns your computer into a
web server
Microsoft IIS and PWS are free web
server components

Internet Information Services

IIS is a set of Internet-based services for


servers created by Microsoft for use with
Microsoft Windows.
IIS comes with Windows 2000, XP, and
Vista. It is also available for Windows NT.
You cannot view Active Server Pages
without running a web-server. To test
your own pages, you should save your
pages in a directory mapped as a virtual
directory, and then use your webbrowser to view the page

How to install IIS on Windows XP and Windows 2000:

On the Start menu, click Settings and select


Control Panel
Double-click Add or Remove Programs
Click Add/Remove Windows Components
Click Internet Information Services (IIS)
Click Details
Select the check box for World Wide Web
Service, and click OK
In Windows Component selection, click Next
to install IIS

Accessing your webpage

Start your web-browser, and enter the


following address into the address-bar.
http://localhost/

You should see a page come up that


tells you more about Microsoft IIS

Test Your Web

After you have installed IIS or PWS follow these


steps:
Look for a new folder calledInetpubon your hard
drive
Open the Inetpub folder, and find a folder
namedwwwroot
Create a new folder, like "MyWeb", under wwwroot
Write some ASP code and save the file as
"test1.asp" in the new folder
Make sure your Web server is running (see below)
Open your browser and type
"http://localhost/MyWeb/test1.asp", to view your
first web page

Creating Virtual Directories

After you have installed the web-server, you


can create virtual directories as follows:
Right-Click on the folder that you wish to
add as a virtual directory.
Select Properties from the context-menu.
In the second tab titled Web Sharing, click
Share this folder, then
Add Alias.
(If you do not see these options enabled,
your web-server is not properly running)

What is localhost?
To connect to a remote computer using its URL, you are
in effect calling it by its hostname.
For example, when you type in http://www.google.com/
you are really asking the network to connect to a
computer named www.google.com. It is called the
hostname of that computer
localhost is a special hostname. It always references
your own machine. So what you just did was to try to
access a webpage on your own machine.
For testing all your pages, you will need to use localhost
as the hostname
There is also a special IP address associated with
localhost, which is 127.0.0.1
http://127.0.0.1/ and would have received the same
page.

What Do Server-Side Scripts Look Like?

Server-side scripts typically start with <% and


end with %> delimiters. The <% is called an
opening tag, and the %> is called a closing
You can insert server-side scripts anywhere in
your webpage - even inside HTML tags.
Server scripts are executed on the server, and
can contain any expressions, statements,
procedures, or operators valid for the
scripting language you prefer to use.

Scripting delimiters
Scripting delimiters <% and %>
wrapped around the VBScript code
these delimit the scripting code that
is executed on the server, not the client.
Script enclosed in scripting delimiters is
not sent to the client; it is processed by
the scripting engine.
Everything outside <% and %> is simply
written to the client.

The response.write Command

The response.write command is used to write


output to a browser.
<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%
Response.Write Hello, World!
%>
</BODY>
</HTML>

Another way

<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%= Hello, World! %>
</BODY>
</HTML>
= sign just after the <%. It has a similar
effect to that of the Response.Write
statement.

@LANGUAGE processing directive

This indicates the scripting engine


needed to interpret the scripting code.
We use VBScript exclusively to develop
our Active Server Pages, although other
scripting languages, such as JavaScript,
may be used. If the @LANGUAGE
processing directive is omitted, VBScript
is the default.

Using JavaScript in ASP

You can use several scripting languages


in ASP. However, the default scripting
language is VBScript
<%@ language="javascript"%>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>

Displaying the Date

<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%= Date %>
</BODY>
</HTML>

Function Date/Time

Using the function Date gives you the current date. And the
function, Time returns the time. To get both, use the function,
Now.
<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%
Response.Write Now
%>
</BODY>
</HTML>

And the output:


7/10/2000 12:35:31 AM

<HTML>
<HEAD>
<TITLE>Hello, World !</TITLE>
</HEAD>
<BODY>
<%
Response.Write Year: & Year (Now)

Response.Write Month: & Month (Now)


Response.Write MonthName: & MonthName
(Month(Now))
Response.Write Hour: & Hour (Now)
Response.Write Minute: & Minute (Now)
Response.Write Second: & Second (Now)
%>
</BODY>
</HTML>

VARIABLES AND CONSTRUCTS


A variable is declared in VBScript using
the Dim keyword.
<%
Dim myVar
%>

Option Explicit

VBScript does not force requiring variable declaration but bugs


that may result are very difficult to detect.
Considering this, we have here a simple directive to make
variable declaration compulsory.
The programmer must explicitly declare all VBScript variables.

<%
Option Explicit
Dim myVar
%>
Example
<%
Option Explicit
Dim Pi
Pi = 3.141592654
%>

Example
<html>
<body>
<%
dim name
name="Donald Duck"
response.write ("My name is: " &
name)
%>
</body>
</html>
My name is: Donald Duck

Declare an array
<html>
<body>
<%
Dim famname(5),i
famname(0) = "Jan Egil"
famname(1) = "Tove"
famname(2) = "Hege"
famname(3) = "Stale"
famname(4) = "Kai Jim"
famname(5) = "Borge"
For i = 0 to 5
response.write(famname(i) & "<br />")
Next
%>
</body>
</html>

Loop through the HTML


headings
<html>
<body>
<%
dim i
for i=1 to 6
response.write("<h" & i &
">Heading " & i & "</h" & i & ">")
next
%>
</body>
</html>

Control structures
Conditional Statements.
Conditional statements are used to perform
different actions for different decisions.
In VBScript we have four conditional statements:
If statement - executes a set of code when a
condition is true
If...Then...Else statement - select one of two sets
of lines to execute
If...Then...ElseIf statement - select one of many
sets of lines to execute
Select Case statement - select one of many sets
of lines to execute

If..Then

If you want to execute only one


statement when a condition is true.
<%
AA="water"
If AA="water" Then
response.write ("I want to drink
water")
End If
%>

If...Then...Else

Use the If...Then...Else statement if you want to execute some code if


a condition is true. Select one of two blocks of code to execute.
<html>
<body>
<%
dim h
h=hour(now())
response.write("<p>" & now())
response.write("</p>")
If h<12 then
response.write("Good Morning!")
else
response.write("Good day!")
end if
%>
</body>
</html>
1/10/2011 1:23:14 AM
Good Morning!

If...Then...Else If

You can use the If...Then...ElseIf statement if you want to select one of many
blocks of code to execute.
<html>
<body>
<%
dim h
h=hour(now())
response.write("<p>" & now())
response.write("</p>")
If h<11 then
response.write("Good Morning!")
elseif
h=12
response.write("Good noon!")
elseif
h=13
response.write(Im having lunch!")
Else
response.write(Im sleeping!")
end if
%>
</body>
</html>

Select Case

You can also use the "Select Case" statement if you want
to select one of many blocks of code to execute.
<%
username=request.form("username")
Select Case username
Case "Peter"
Response.write ("Hello, Peter")
Case "John"
Response.write ("Hello, John")
Case "Joe"
Response.write ("Hi, Joe")
Case Else
Response write ("I do not know you")
End Select
%>

Looping Statements
Looping statements are used to run the same
block of code a specified number of times.
In ASP t we have four looping statements:
For...Next loop - runs code a specified number
of times
For Each...Next loop - runs code for each item
in a collection or each element of an array
Do While...Loop
While...Wend statement - Do not use it - use
the Do...Loop statement instead

For...Next loop example


<%
For I = 1 to 10
Response.Write Number = & I & vbCrLf
Next
%>
And the output ...
Number = 1
Number = 2
Number = 3
vbCrLf causes the output to continue on the
next line.

For Each...Next loop

<%
For Each Member in Team
Response.Write Member
Next
%>

Do While...Loop

Define a condition and one or more


instructions

<%
mynumber=0
Do While mynumber<10
response.write("Hello<HR>")
mynumber=mynumber+1
Loop
%>

Do Until....Loop

Quite similar to the Do-while , it also


includes a condition and one or more
instructions
<%
mynumber=0
Do Until mynumber=10
response.write("Hello<HR>")
mynumber=mynumber+1
Loop
%>

SUBROUTINES AND FUNCTIONS

VBScript allows you to define and use your own Subroutines,


Functions

Subroutines
Subroutines are defined via the Sub keyword.
<%
Sub SayHello
Response.Write Hello !
End Sub
%>

A subroutine may accept parameters too, which can be of


any type.
<%
Sub SayHelloTo (Person)
Response.Write Hello, & Person & !
End Sub

Example

<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>

<p>Result: <%call vbproc(3,4)%></p>

</body>
</html>

Functions

Functions are defined similar to


Subroutines:
<%
Function Add (A, B)
Add = A + B
End Sub
%>

Example
<%
Function Calculate (A, B, Op)
Select Case Op
Case +
Calculate = A + B
Case -
Calculate = A - B
Case *
Calculate = A * B
Case /
Calculate = A / B
End Select
End Function

<%
Response.Write Calculate(2, 3, +)
Response.Write Calculate(2, 3, -)
%>

THE OBJECT MODEL/ASP Objects

ASP is a scripting environment revolving


around its Object Model. An Object Model
is simply a hierarchy of objects that you
may use to get services from.
In ASP, all commands are issued to
certain inbuilt objects, which include
Request,
Response,
Server
Session
Application

Request object
The Request object is commonly used
to access the information passed by a
get or post request. This information
usually consists of data provided by the
user in an XHTML form. The Request
object provides access to information
(such as cookies) that is stored on
aclients machine. This object also
provides access to binary information
(e.g., afile upload).

Response object
The Response object sends
information, such as XHTML or text
to the client.
The Response object is used to send
information to the user. The Response
object supports only Cookies as a
collection (to set cookie values). The
Response object also supports a
number of properties and methods

Server object
The Server object provides access to
methods and properties on the server
The Server object provides access to
methods and properties on the server.
Most of these methods and properties
serve as utility functions.

The Session object

You can use the Session object to store


information needed for a particular usersession. Variables stored in the Session
object are not discarded when the user
jumps between pages in the application;
instead, these variables persist for the entire
user-session
One common use for the Session object is to
store user preferences. For example, if a
user indicates that they prefer not to view
graphics, you could store that information in
the Session object.

The Application object

The Application object can store


information that persists for the entire
lifetime of an application (a group of
pages with a common root).Generally, this
is the whole time that the IIS server is
running.
This makes it a great place to store
information that has to exist for more than
one user (such as a page counter)
You can use the Application object to
share information among all users of a
given application

Using Variables, and Forms in Active Server Pages

Forms are a convenient way to communicate


with visitors to your Web site
ASP is also used to process form input. Data
entered into a form can be sent to the server,
processed and then sent back to the client in a
different format. For example, an ecommerce
site may use this to verify a customers order
information.
With forms, there are two steps: first you create
the form, and then you process it

Processing Forms
GET and POST
Form is submitted may be one of the
two methods: GET or POST.

GET method and


Request.QueryString collection
GET may be used for small amounts of data
the reason being that, the data items are appended to the
URL by your browser.
e.g
http://www.greetings.com/show.asp?
CardID=128762173676
Any data that you pass via a GET can be retrieved in your
script by using the Request.QueryString collection
To display the contents of each field in the form, type:
Request.Querystring (fieldname) where fieldname is the
name of the field.
e.g Request.QueryString (FirstName)

POST method and


Request.Form Collection
Stick to POST for your forms, and be sure to
use the Request.Form collection to access
them
To display the contents of each field in the
form, type:
Request.Form(fieldname) where
fieldname is the name of the field.
e.G
Request.Form (FirstName)
Request.Form (LastName)

Request.QueryString
<html>
<form method="get" action="simpleform.asp">
First Name: <input type="text" name="fname" /><br />
Last Name: <input type="text" name="lname" /><br
/><br />
<input type="submit" value="Submit" />
</form>
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>

The Request.Form Collection example

<html>
<head>
<form method="post" action="myform.asp">
First Name: <input type="text" name="name1" /><br />
Last Name: <input type="text" name="email1" /><br /><br />
<input type="submit" value="Submit" />
</form>
</head>
<body>
Welcome
Your name is <% =Request.Form("name1") %> <BR />
Your email is <% =Request.Form("email1") %>
</body>
</html>

<html>
<body>
<form method="post" action="simpleform2.asp">
FirstName: <input type="text" name="fname"></br >
SeconName: <input type="text" name="sname"></br >
Email: <input type="text" name="email"></br >
Password: <input type="text" name="pword"></br >
<p>Please specify your Gender:</p>
Male<input type="radio" name="gender" value="male">
Female<input type="radio" name="gender" value="Female">
<p><h2>Which package would you like</h2></p>
Adventure<input name="package" type="checkbox" value="adventure" />
Surfing<input name="package" type="checkbox" value="seasurfing" />
<p><h2>Select your continent</h2></p>
<select name="continent">
<OPTION selected="selected">select-continent</OPTION>
<OPTION>South America</OPTION>
<OPTION>North America</OPTION>
<OPTION>Australia</OPTION>
<OPTION>Artica</OPTION>
<OPTION>NewZealand</OPTION>
<OPTION>Europe</OPTION>
<OPTION>Asia</OPTION>
</SELECT>
<input type="submit" value="Submit">
</form>
Welcome
<%
response.write(Request.Form("fname"))
response.write(" " & Request.Form("sname"))
%><br>
Your Email address is <%response.write(Request.Form("email"))%>
and your password is <%response.write(" " & Request.Form("pword"))%><br>
Your are a <%response.write(Request.Form("gender"))%><br>
Your favourite game is <%response.write(Request.Form("package"))%>
and you come from <%response.write(Request.Form("continent"))%>
</body>
<html>

HTML file ("form_response.html")


form_response.html
<html>
<head><title>Asking for
information</title></head>
<body>
<form method="post" action="form_response.asp">
Your name: <input type="text" name="name"
size="20"><BR>
Your email: <input type=text" name="email"
size="15"><BR>
<input type="Submit" value="Submit">
</form>
</body>
</html>

form_response.asp

<html>
<head><title>Responding to a
form</title></head>
<body>
Your name is <%
=Request.Form("name") %> <BR>
Your email is <%
=Request.Form("email") %>
</body>
</html>

Creating a Variable
you may want to create a variable and insert that variable
in different places of your response page
<% TheName = Request.Form("CatName") %>
<form action="demo_reqquery.asp"
method="get">
Your name: <input type="text" name="fname"
size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>

A form with method="get"


<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname"
size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>

A form with method="post"


<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname"
size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br />")
Response.Write("How are you today?")
End If
%>
</body>
</html>

Another example

<html>
<%
dim cars
cars=Request.Form("cars")
%>
<body>
<form action="demo_radiob.asp" method="post">
<p>Please select your favorite car:</p>
<input type="radio" name="cars
<% if cars="Volvo" then Response.Write("checked")%>
value="Volvo">Volvo</input>
<br />
<input type="radio" name="cars
<%if cars="Saab" then Response.Write("checked")%>
value="Saab">Saab</input>
<br />
<input type="radio" name="cars"
<%if cars="BMW" then Response.Write("checked")%>
value="BMW">BMW</input>
<br /><br />
<input type="submit" value="Submit" />
</form>
<%
if cars<>"" then
Response.Write("<p>Your favorite car is: " & cars & "</p>")
end if
%>
</body>
</html>

nameandcolor.html

<html>
<head><title>Name and Color</title></head>
<body>

<FORM ACTION="nameandcolor.asp" METHOD=POST>


Let me know your Name and Favorite Color:
<P>YOUR NAME:
<INPUT TYPE="TEXT" NAME="YOURNAME" SIZE=20>
<P>COLOR:
<INPUT TYPE="RADIO" NAME="COLOR" VALUE="1"
CHECKED>Red
<INPUT TYPE="RADIO" NAME="COLOR" VALUE="2">Green
<INPUT TYPE="RADIO" NAME="COLOR" VALUE="3">Blue
<P>
<INPUT TYPE="SUBMIT" VALUE="OK">
</FORM>
</body>
</html

Now, create an ASP file ("nameandcolor.asp")


nameandcolor.asp
<html>
<head><title>Name and Color</title></head>
<body>
<% TheName = Request.Form("YOURNAME) %>
<% colornumber = Request.Form("COLOR") %>
Hi, <% =Thename %>.<BR>
I know your favorite color is
<% if colornumber = "1" then %>
red
<% end if %>
<% if colornumber = "2" then %>
green
<% end if %>
<% if colornumber = "3" then %>
blue
<% end if %>.
</body>
</html>

Example
backgroundform.html
<html>
<head><title>Chose background color</title></head>
<form action="backgroundresponse.asp" method="post">
Which color do you prefer to use as your background?
<BR>
<input type="radio" name="kindofcolor" value="defined" checked>
Defined color
<select name="definedcolor">
<option value="#FFFFFF">White</option>
<option value="#FF0000">Red</option>
<option value="#00FF00">Green</option>
<option value="#0000FF">Blue</option>
</select>
<BR>
<input type="radio" name="kindofcolor" value="custom">
Custom color
<input type="text" size="8" name="mycolor"></input>
<BR><input type="Submit" value="Submit"></input>
</form>
</body>
</html>

backgroundresponse.asp

<%
kindofcolor=Request.form("kindofcolor")
Select Case kindofcolor
case "defined"
colorofbackground=Request.form("definedcolor")
Select Case colorofbackground
case "#FFFFFF"
texttoshow="White"
case "#FF0000"
texttoshow="Red"
case "#00FF00"
texttoshow="Green"
case "#0000FF"
texttoshow="Blue"
End select
case "custom"
colorofbackground=Request.form("mycolor")
texttoshow="Custon color"
End select
%>
<html>
<head><title>Chose background color</title></head>
<body bgcolor="<% =colorofbackground %>">
<center>
<H1><% =texttoshow %></H1>
</center>
</form>
</body>
</html>

ADOIntroduction

ADO can be used to access databases from


your web pages.
What is ADO?
ADO is a Microsoft technology
ADO stands forActiveXDataObjects
ADO is a Microsoft Active-X component
ADO is automatically installed with Microsoft
IIS
ADO is a programming interface to access
data in a database

Accessing a Database from an ASP Page

The common way to access a database


from inside an ASP page is to:
Create an ADO connection to a database
Open the database connection
Create an ADO recordset
Open the recordset
Extract the data you need from the
recordset
Close the recordset
Close the connection

ADODatabase Connection

Before a database can be accessed from


a web page, a database connection has
to be established.
Create a DSN-less Database
Connection
The easiest way to connect to a database
is to use a DSN-less connection. A DSNless connection can be used against any
Microsoft Access database on your web
site.

An ODBC Connection to an MS Access Database

Here is how to create a connection to a MS Access


Database:
Open theODBCicon in your Control Panel.
Choose theSystem DSNtab.
Click onAddin the System DSN tab.
Selectthe Microsoft Access Driver. ClickFinish.
In the next screen, clickSelectto locate the
database.
Give the database aDataSourceName (DSN).
ClickOK.
Note that this configuration has to be done on the
computer where your web site is located

Create an ODBC Database Connection

If you have an ODBC database called


"students" you can connect to the database
with the following ASP code:
<%
set
conn=Server.CreateObject("ADODB.Conne
ction")
conn.Open "students"
%>
With an ODBC connection, you can connect to
any database, on any computer in your
network, as long as an ODBC connection is
available.

ADORecordset

To be able to read database data, the data


must first be loaded into a recordset.
The ADO Recordset object is used to hold
a set of records from a database table.
After an ADO Database Connection has
been created, it is possible to create an
ADO Recordset.
Suppose we have a database named
"students", we can get access to the
"studentmarks" table inside the database
with the following lines:

Recordset
Suppose we have a database named "students", we
can get access to the "studentmarks" table inside
the database with the following lines:
<%
set
conn=Server.CreateObject("ADODB.Connectio
n")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/marks/students.mdb"
set
rs=Server.CreateObject("ADODB.recordset")
rs.Open "studentmarks", conn
%>

Create an ADO SQL Recordset

We can also get access to the data in the "


studentmarks " table using SQL:
<%
set
conn=Server.CreateObject("ADODB.Connecti
on")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/marks/students.mdb"
set
rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from studentmarks", conn
%>

Extract Data from the Recordset

After a recordset is opened, we can extract data from


recordset.
Suppose we have a database named "marks", we can get
access to the " studentmarks " table inside the database
with the following lines:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/marks/students.mdb"
set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from studentmarks", conn
for each x in rs.fields
response.write(x.name)
response.write(" = ")
response.write(x.value)
next

Display the Field Names and Field Values

<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/marks/students.mdb"
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT * FROM studentmarks", conn
do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
rs.MoveNext
loop
rs.close
conn.close
%>
</body>
</html>

Display the Field Names and Field Values in an HTML Table

We can also display the data from the "


studentmarks" table inside an HTML
table with the following lines (remember
to save the file with an .asp extension):

<html>
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/marks/students.mdb"
set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Studentname, Marks FROM studentmarks"
rs.Open sql, conn
%>
<table border="1" width="50%">
<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>

Add Headers to the HTML Table

We want to add headers to the HTML


table to make it more readable
(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:/marks/students.mdb"
set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Studentname, studentmarks FROM Customers"
rs.Open sql, conn
%>
<table border="1" width=50%">
<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>

ADOAdd Records

We may use the SQL INSERT INTO


command to add a record to a table in a
database
Add a Record to a Table in a Database
We want to add a new record to the
studentmarks table in the marks
database. We first create a form called
enter.html that contains the fields we
want to collect data from

Enter Form
<html>
<body>
<form method="post" action="test2.asp">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr><tr>
<td>Course Name:</td>
<td><input type="text" name="cname"></td>
</tr><tr>
<td>Marks:</td>
<td><input type="text" name="marks"></td>
</tr>
</table>
<br /><br />
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>
</body>
</html>

ADOAdd Records

When the user presses the submit button


the form is sent to a file called
test2.asp". The
test2.asp" file contains the code that
will add a new record to the
studentmarks table:

test2.asp"
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.mode=adModeReadWrite
conn.Open "c:/marks/students.mdb"
Set Recordset=Server.CreateObject("ADODB.Recordset")
sql="INSERT INTO studentmarks(StudentName,CourseName,Marks)
VALUES('"&Request.Form("name")&"','"&Request.Form("cname")&"','"&Request.Form("marks")
&"')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
%>
</body>
</html>

Add a Record to a Table in a


Database
We want to add a new record to the
booking table in the marks database. We
first create a form called
customerdata.html that contains the
fields we want to collect data from

Customerdata.html
<html>
<body>
<form method="post" action="cust_process.asp">
<table border="0" width="40%">
<tr>
<td>CustomerID:</td>
<td><input type="text" name="custid"></td>
</tr><tr>
<td>Company Name:</td>
<td><input type="text" name="compname"></td>
</tr><tr>
<td>Contact Name:</td>
<td><input
type="text"
name="contname"></td>
</tr><tr>
<td>Address:</td>
<td><input type="text"
name="address"></td>
</tr><tr>
<td>City:</td>
<td><input type="text"
name="city"></td>
</tr><tr>
<td>Postal Code:</td>
<td><input type="text"
name="postcode"></td>
</tr><tr>
<td>Country:</td>
<td><input type="text" name="country"></td>
</tr>
</table>
<br /><br />
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>
</body>
</html>

When the user presses the submit


button the form is sent to a file called
cust_process.asp". The
cust_process.asp " file contains the
code that will add a new record to the
booking table:

cust_process.asp
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/marks/booking.mdb"
sql="INSERT INTO
book(customerID,companyname,contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
%>
</body>
</html>

Anda mungkin juga menyukai