using active server page (asp) to create simple web-database

Post on 03-Feb-2022

6 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

IT in Education e-Leadership & Management Series

Using Active Server Page (ASP) to create Simple

Web-database Application

Speaker�PAU CHUNG WAI (Half-seconded Teacher)

2

IT Management FWG’s Blog

http://edblog.hkedcity.net/itman

3

Reference Site

� http://www.w3schools.com

4

Part 1: Introduction

5

Introduction to Dynamic Web Page

� Dynamic means content on a web page can change in response to different context or conditions.

� More interactive than static web page

� Two ways:

� Client-side Scripting (e.g. JavaScript, VBScript)

� Server-side Scripting (e.g. PHP, Perl, ASP, JSP)

6

What is ASP?

� ASP stands for Active Server Pages

� ASP is a program that runs inside IIS

� IIS stands for Internet Information Services

� IIS comes as a free component with Win XP and Vista

7

How does ASP differ from HTML?

� When a browser requests an HTML file, the server returns the file.

� When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as

plain HTML.

8

How does ASP differ from HTML?

Web Server

Client

Request

ASP Engine

Response

displayed in browser

9

Advantages of using ASP?

� Dynamically edit, change or add any content of a Web page

� Access any data or databases and return the results to a browser

� Provide security since your ASP code cannot be viewed from the browser

10

Part 2: How to setup a Web Server?

11

How to install IIS in Win XP?

� To run ASP, IIS must be installed.

� Follow these steps to install IIS on Windows XP:� 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.

� After you have installed IIS, make sure you install all patches for bugs and security problems.

12

13

14

After Installation, you can find the IIS program icon in System Tools (������):

15

Right-click and then select “Properties (��)”

16

Primary Document Folder (Can be changed)

17

Test your Web

� Follow these steps after you have installed IIS:

� Look for a new folder called Inetpub on your hard drive.

� Open the Inetpub folder, and find a folder named wwwroot.

� Create a new folder, “ASP", under wwwroot.

� Copy all the sample files to this folder

� Make sure your Web server is running.

� Open your browser and type

“http://localhost/ASP/testing.asp"

to view your first web page.

18

How to install IIS in Windows Vista?

1. On the Start menu, click Settings and select Control Panel.

2. Select Turn Windows Features On or Off from Programs and Features.

3. Select Internet Information Services. Expand the tree nodes of IIS, check the options that you want to turn on. (You must turnon ASP feature)

4. Then click OK to install IIS.

19

How to install IIS in Windows Vista?

20

How to install IIS in Windows Vista?

TRUE

21

How to install IIS in Win Server 2003?

1. When you start the Windows Server 2003, you should see the Manage Your Server wizard

2. If the wizard is not displayed, go to Administrative Tools, and select Manage Your Server

3. In the wizard, click Add or Remove a Role, click Next

4. Select Custom Configuration, click Next

5. Select Application Server role, click Next

6. Select Enable ASP.NET, click Next

7. Now, the wizard may ask for the Server 2003 CD. Insert the CD and let it run until it is finished, then click the Finish button

8. The wizard should now show the Application Server role installed

22

How to install IIS in Win Server 2003?

9. Click on Manage This Application Server to bring up the Application Server Management Console (MMC)

10. Expand the Internet Information Services (IIS) Manager, then expand your server, and then the Web Sites folder

11. You should see the Default Web Site, and it should not say (Stopped)

12. IIS is running!

13. In the Internet Information Services (IIS) Manager click on the Web Service Extensions folder

14. Here you will see that Active Server Pages are Prohibited (this is the default configuration of IIS 6)

15. Highlight Active Server Pages and click the Allow button

16. ASP is now active!

23

Part 3: Basic ASP Syntax

24

Basic Syntax

� ASP file normally contains HTML tags

� Also contains server scripts, surrounded by the delimiter <% and %>

� Server scripts are executed on the server

� Results are plain HTML codes

� Source codes not viewed by the web browser

25

Example 1A

<html>

<body>

<%

response.write(“Hello World!”)

%>

</body>

</html>

example1a.asp

26

Example 1B

<html>

<body>

<%

=“hello World!”

%>

</body>

</html>

example1b.asp

27

Example 2A

<html>

<body>

<%

response.write(“The time now is ” & now())

%>

</body>

</html>

example2a.asp

28

Example 2B

<html>

<body>

<%

response.write(formatdatetime(now(),1) & "<br>")

response.write(formatdatetime(now(),2) & "<br>")

response.write(formatdatetime(now(),3) & "<br>")

response.write(formatdatetime(now(),4) & "<br>")

%>

</body>

</html>

example2b.asp

29

Variable

� A variable is used to store information.

� If the variable is declared outside a procedure it can be changed by any script in the ASP file.

� If the variable is declared inside a procedure, it is created and destroyed every time the procedure is executed.

30

Example 3

<%

X = “Hello World!”

Sub Display()

Dim X

X = “Welcome!”

Response.write(X)

End Sub

%>

<html>

<body>

<% call display() %> <br>

<% =X %>

</body>

</html>

example3.asp

31

Procedure

� You can call both a JavaScript procedure and a VBScript procedure in an ASP file

32

Example 4 – Calling a VBScript Procedure

<html><head><%sub vbproc(num1,num2)

response.write num1*num2end sub%></head><body><p>The result of 3 * 4 is <%call vbproc(3,4)%>.</p></body></html>

example4.asp

33

Example 5 – Calling a JavaScript Procedure

<%@ language=“JavaScript”%><html><head><%function jsproc(num1,num2)

{Response.Write(num1*num2)

}%></head><body><p>The result of 3 * 4 is <%jsproc(3,4)%>.</p></body></html>

example5.asp

34

Session Object

� The Session object is used to store information about, or change settings for a user session.

� Variables stored in the Session object hold information about one single user, and are available to all pages in one application.

35

Example 6

<html><head><%Session(“Username”) = “Raymond”%></head><body><p>My name is <%=session(“Username”)%>.</p></body></html>

Keep the browser open, browse another ASP file called “example7.asp”.

example6.asp

36

Example 7

<html><head></head><body><p>My name is <%=session(“Username”)%>.</p></body></html>

Now, close all the browsers, Open “example7.asp” again. What do you see?

example7.asp

37

Session Object

� A session ends if a user has not requested or refreshed a page for a specified period. (By default, this is 20 minutes)

� You can set the timeout property:

<% Session.Timeout=5 %>

38

Session Object

� To end a session immediately, you may use the Abandon method:

<% Session.Abandon %>

Can you name one application of the Session object?

39

Application Object

� The Application object is used to store and access variables from any page, just like the Session object.

� The difference is that ALL users share one Application object, while with Sessions there is one Session object for EACH user.

� The Application object in ASP is used to tie these files together.

40

Application Object

� You can create Application variables in “Global.asa”

<script language="vbscript" runat="server">

Sub Application_OnStart

application("vartime")=""

application("users")=1

End Sub

</script>

41

What is Global.asa?

� The “Global.asa” file is an optional file that can contain declarations of objects, variables, and methods.

� It can be accessed by every page in an ASP application.

� The “Global.asa” file must be stored in the root directory of the ASP application, and each application can only have one “Global.asa” file.

42

Example 8

<script language="vbscript" runat="server">Sub Application_OnStart

Application("visitors")=0 End Sub

Sub Session_OnStart Application.Lock Application("visitors")=Application("visitors")+1Application.UnLock

End Sub

Sub Session_OnEnd Application.Lock Application("visitors")=Application("visitors")-1 Application.UnLock

End Sub</script>

Global.asa

Save this file in the root directory (i.e. c:\inetpub\wwwroot\)

Save this file in the root directory (i.e. c:\inetpub\wwwroot\)

This “Global.asa” file counts the number of current visitors

43

Example 8

<html><head></head><body><p>

There are <%response.write(Application("visitors"))%>

online now!</p></body></html>

example8.asp

To display the number of current visitors in an ASP file:

44

The #include Directive

� You can insert the content of one ASP file into another ASP file.

� The #include directive is used to create functions, headers, footers, or elements that will be reused on multiple pages.

45

Example 9

<html>

<body>

<h3>Words of Wisdom:</h3>

<p><!--#include file="wisdom.inc"--></p>

<h3>The time is:</h3>

<p><!--#include file="time.inc"--></p>

</body>

</html>

example9.asp

46

Example 9

"One should never increase, beyond what is necessary, the number of entities required to explain anything."

<%

Response.Write(Time)

%>

Here is the content of "wisdom.inc" file:

Here is the content of “time.inc" file:

47

Part 4: Web forms handling

48

User Input

� Form is usually used to collect information from user. For example:

<html><body><form action=“display.asp" method="get">Your name: <input type="text" name="fname" size="20"><input type="submit" value="Submit"></form></body></html>

� Get or Post method could be used.

� Action defines the ASP file that accepts the user inputs.

49

Request Object

� The Request object may be used to retrieve user information from forms. For example:

<html>

<body>

<form action=" example10.asp" method="get">

Your name: <input type="text" name="fname" size="20">

<input type="submit" value="Submit">

</form>

<%

fname=Request("fname")

If fname<>"" Then

Response.Write("Hello " & fname & "!")

End If

%>

</body>

</html>

example10.asp

Let’s try another method - “Post”

50

Classwork 1

� Create the following ASP file that accepts name and sex as input, then output the text as indicated.

51

Using DreamWeaver as editor

� Use design view to create the layout of the web page in WYSIWYG mode.

� Change to code view, add ASP scripts

� Preview (press F12) the web page and make changes

Let’s see a demonstration!

52

Site Definition in DreamWeaver 1/3

� When you press F12 to preview the ASP file, you will be asked to define the location of testing server.

53

Site Definition in DreamWeaver 2/3

Define the site name & the root folder (c:/inetpub/wwwroot) for the ASP files

54

Site Definition in DreamWeaver 3/3

Define the server model (ASP VBScript) and the access method (Local/Newtork).

Then, click OK to confirm.

55

Part 5: Database Manipulation

56

Introduction to ADO

� ADO stands for Active-X Data Object

� It is a Microsoft Active-X component

� It is a programming interface to access data in a database

57

Introduction to ADO

� Common way to access a database from inside an ASP page:

� Create an ADO connection to a database

� Open the database connection

� Create an ADO recordset (SQL is needed)

� Open the recordset

� Extract the data you want from the recordset (you need to know how to use SQL)

� Close the recordset

� Close the connection

58

Example 11� Open a MS access database called “student.mdb” in

the ASP folder.

“ ClassTeacher” table

“Student” Table

59

Example 11

� This example extract all student records from the table “Student”, then display them on a web page

� To do so, the following SQL is required:

select * from student

60

<%

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

conn.Open “c:\inetpub\wwwroot\asp\student.mdb"

set rs=Server.CreateObject("ADODB.recordset")

rs.Open "Select * from student", conn

while not rs.eof

for each x in rs.fields

response.write(x.name & " = ")

response.write(x.value)

response.write("<br>")

next

response.write("<p>")

rs.movenext

wend

rs.close

conn.close

%>

example11a.asp

Must specify theabsolute pathof the database

SQL used to extract data from table

61

Alternative way to define the location of database

<%

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

dbPath = Server.MapPath(“student.mdb")

conn.Open dbPath

set rs=Server.CreateObject("ADODB.recordset")

rs.Open "Select * from student", conn

%>

The Server.MapPath() function can determine the absolute path of the database.

example11b.asp

62

Example 12

� Display the student records of 1B in an HTML tables

� Only “classname”, “classno” and “enname” are displayed

� This time, the following SQL should be used:

Select classname, classno, enname from Student where classname = ‘1B’

63

<%

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

dbPath = Server.MapPath(“student.mdb")

conn.Open dbPath

set rs=Server.CreateObject("ADODB.recordset")

rs.Open "Select classname, classno, enname from student where classname = ‘1B’", conn

%>

<table border="1" width="100%">

<tr> <% for each x in rs.fields %>

<th> <% response.write(x.name) %></th>

<% next %> </tr>

<% while not rs.eof %>

<tr> <% for each x in rs.fields %>

<td> <% response.write(x.value) %></td>

<% next

rs.movenext %>

</tr>

<% wend

rs.close

conn.close %>

</table>

example12a.asp

64

<%

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

dbPath = Server.MapPath(“student.mdb")

conn.Open dbPath

set rs=Server.CreateObject("ADODB.recordset")

rs.Open "Select classname, classno,enname from student where classname = '1B'", conn

%>

<table border="1" width="100%">

<tr> <th> Class </th><th> Class Number </th><th> Name </th></tr>

<% while not rs.eof %>

<tr> <td> <%=rs(“classname”)%> </td>

<td> <%=rs(“classno”)%> </td>

<td> <%=rs(“enname”)%> </td> </tr>

<%

rs.movenext

wend

rs.close

conn.close

%>

</table>

example12b.asp

65

Example 13

� Display the student records of 1B in an HTML tables

� The output should also display the class teacher of 1B

� This time, the following SQL should be used:

Select student.classname, classno, enname, tname from Student, ClassTeacher where student.classname = classteacher.classname and student.classname = '1B'

66

<%

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

dbPath = Server.MapPath(“student.mdb")

conn.Open dbPath

set rs=Server.CreateObject("ADODB.recordset")

rs.Open "Select student.classname, classno, enname, tname from Student, ClassTeacher where student.classname = classteacher.classname and student.classname = '1B'", conn

%>

<table border="1" width="100%">

<tr> <th> Class </th><th> Class Number </th><th> Name </th><th> Class Teacher </th></tr>

<% while not rs.eof %>

<tr> <td> <%=rs(“classname”)%></td><td> <%=rs(“classno”)%> </td>

<td> <%=rs(“enname”)%> </td><td> <%=rs(“tname”)%> </td> </tr>

<% rs.movenext

wend

rs.close

conn.close %>

</table>

example13.asp

67

Classwork 2� Create an ASP file that display a class list of a specified class

chosen from the database “Student.mdb”.

68

Adding record to table

� You may use the SQL INSERT INTOcommand to add a record to a table in a database.

� A form is needed to collect information.

� The information collected is then sent to another ASP file for manipulation.

69

Example 14

� To add a new record to “Student”, two files are needed.

<html>

<body><form method="post" action="example14_add.asp">

<table>

<tr><td>Registration Number:</td><td><input name="regno"></td></tr>

<tr><td>Name:</td><td><input name="enname"></td></tr>

<tr><td>Class:</td><td><input name="classname"></td></tr>

<tr><td>Class No:</td><td><input name="classno"></td></tr>

<tr><td>Sex:</td><td><input name="sex"></td></tr>

<tr><td>House:</td><td><input name="house"></td></tr>

</table>

<p>

<input type="submit" value="Add New">

<input type="reset" value="Cancel">

</form></body>

</html>

example14.asp

70

<html>

<body>

<%

set conn=Server.CreateObject("ADODB.Connection")

conn.Provider="Microsoft.Jet.OLEDB.4.0"

conn.Open(Server.MapPath("student.mdb"))

sql="INSERT INTO student (regno,enname,classname,classno,sex,house) VALUES ("

sql=sql & "'" & Request("regno") & "', " & "'" & Request("enname") & "',"

sql=sql & "'" & Request("classname") & "'," & Request("classno") & ","

sql=sql & "'" & Request("sex") & "'," & "'" & Request("house") & "')"

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>

example14_add.asp

71

Problem

� 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 the server.

� To solve this problem, right-click the .mdb file and select Properties. Go to the Securitytab and set the access-rights there.

72

You must grant the “Write” access right to the Internet guest account

73

74

Updating record in table

� You may use the SQL UPDATE command to update a record in a table in a database.

� Again, 2 files are needed.

���� See Example 15

75

<html><%set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLEDB.4.0"conn.Open(Server.MapPath("student.mdb"))set rs=Server.CreateObject("ADODB.Recordset")%><body>

<Form method="get" action="example15.asp">Regno: <input name="searchname"> <input type="submit" value="Search"></Form>

<% if request("searchname") <> "" then

rs.open "SELECT * FROM student where regno = '" & request("searchname") & "'",conn if not rs.eof then

%>

<form method="post" action="example15_update.asp"><table><tr><td>Registration Number:</td><td><%=rs("regno")%><input type="hidden" name="regno" value=<%=rs("regno")%>></td></td></tr><tr><td>Name:</td><td><input name="enname" value=<%=rs("enname")%>></td></tr><tr>

example15.asp

Search box for reg.no.

See if the specified reg.

no. is found in the table

Hidden field that will be

passed to the update file

76

<td>Class:</td><td><input name="classname" value=<%=rs("classname")%>></td></tr><tr><td>Class No:</td><td><input name="classno" value=<%=rs("classno")%>></td></tr><tr><td>Sex:</td><td><input name="sex" value=<%=rs("sex")%>></td></tr><tr><td>House:</td><td><input name="house" value=<%=rs("house")%>></td></tr></table><p><input type="submit" value="Update"> <input type="reset" value="Cancel"></form>

<%else

response.write("Record not found!")end if

end if%>

</body></html>

77

<html><body><%set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLEDB.4.0"conn.Open(Server.MapPath("student.mdb"))set rs=Server.CreateObject("ADODB.Recordset")sql="UPDATE student SET enname = '" & request("enname") & "',"sql=sql & "classname = '" & Request("classname") & "',"sql=sql & "classno = " & Request("classno") & ","sql=sql & "sex = '" & Request("sex") & "',"sql=sql & "house = '" & Request("house") & "'"sql=sql & "WHERE regno = '" & Request("regno") & "'"

on error resume nextconn.Execute sqlif err <> 0 then

response.write("No update permissions!")else

response.write("Record " & Request("regno") & " was updated!")end if conn.close%></body></html>

example15_update.asp

78

79

Deleting record from table

� You may use the SQL DELETE command to delete a record in a table in a database

80

<html><%set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLEDB.4.0"conn.Open(Server.MapPath("student.mdb"))set rs=Server.CreateObject("ADODB.Recordset")%><body>

<Form method="get" action="example16.asp">

Regno: <input name="searchname"> <input type="submit" value="Search"></Form>

<% if request("searchname") <> "" then

rs.open "SELECT * FROM student where regno = '" & request("searchname") & "'",conn

if not rs.eof then%>

Example 16

example16.asp

81

<form method="post" action="example16_delete.asp"><table><tr><td>Registration Number:</td><td><%=rs("regno")%><input type="hidden" name="regno" value=<%=rs("regno")%>></td></tr><tr><td>Name:</td><td><%=rs("enname")%></td></tr><tr><td>Class:</td><td><%=rs("classname")%></td></tr><tr><td>Class No:</td><td><%=rs("classno")%></td></tr><tr><td>Sex:</td><td><%=rs("sex")%></td></tr><tr><td>House:</td><td><%=rs("house")%></td></tr></table><p><input type="submit" value="Delete"> <input type="reset" value="Cancel"></form>

<% elseresponse.write("Record not found!")

end ifend if %>

82

<html><body><%set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLEDB.4.0"conn.Open(Server.MapPath("student.mdb"))set rs=Server.CreateObject("ADODB.Recordset")sql="DELETE FROM student WHERE regno = '" & Request("regno") & "'"

on error resume nextconn.Execute sqlif err <> 0 then

response.write("No update permissions!")else

response.write("Record " & Request("regno") & " was deleted!")end if conn.close%></body></html>

example16_delete.asp

83

84

Congratulation!

You have learnt the basics of ASP and you

are now able to access database online.

85

Some School Applications …

� Online Class List

http://localhost/samples/classlist/

� Download file at specific time

http://localhost/samples/download/

� Online Timetablehttp://localhost/samples/tt/

� Online Booking System

http://localhost/rbs/

86

More Internet References

� ASP �������

http://www.spps.tp.edu.tw/documents/memo/asp/asp.htm

� Homepage for ASP 3.0 (ASP3Wiki)http://asp3wiki.wrox.com/wiki/

� ��

http://www.blueshop.com.tw

87

IT Management FWG’s Blog

http://edblog.hkedcity.net/itman

top related