Advertise here.
Showing posts with label ASP. Show all posts
Showing posts with label ASP. Show all posts

Tuesday, 28 August 2012

ASP Lesson #5 - Using a Database


Creating an Access database

First we will create a database in Access called Employees.mdb. This will have a table called Employee and here is what it should look like:

Employee
EmpNo
FirstName
LastName

Insert the following values into the tables:

Employee
1JohnSmith
2MaryJones
3JamesKing


The Connection object

The first thing to do before you can use a database is create a Connection object.

Dim cn
Set cn = Server.CreateObject("ADODB.Connection")

Next set the ConnectionString property of the Connection and open the Connection.

cn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " & Server.MapPath("Employees.mdb")
cn.Open

The RecordSet object

We now need a RecordSet object to store the results of a query. You must create the RecordSet in a way similar to how you created a Connection.

Dim rs
Set rs = Server.CreateObject("ADODB.RecordSet")

Before you can go on with the next step you need to copy C:\Program Files\Common Files\System\ado\adovbs.inc to C:\Inetpub\wwwroot. Also add the following line after <%Option Explicit%>:

<!--#include file="adovbs.inc"-->

Now we can open the RecordSet like this:

rs.Open "SELECT * FROM Employee", cn, adOpenStatic, adLockOptimistic

The first parameter in quotes after rs.Open is a SQL statement that says all records from the Employee table must be retrieved. The second parameter is the connection. The Third parameter is the CursorType and the Fourth parameter is the LockType.

Reading from a RecordSet

Now that we have opened the RecordSet we can read values from it. We will use a loop to write the first name of each employee in the Employee table on the page.

While Not rs.EOF
   Response.Write rs("FirstName") & "<br>"
   rs.MoveNext
Wend

The Find command can be used to find a specific record.

rs.Find "LastName = 'King'"

Writing to a RecordSet

You can change the value of a field in the RecordSet by setting its value in the same way as you set the value of a variable. After you have set the value you have to use the Update command or the changes will not happen.

rs("FirstName") = "Mike"
rs.Update

Cleaning up

You must always close all Connections and RecordSets when you are finished using them. You must also set them equal to Nothing. If you do not then they will stay in the server's memory until it has not memory left.

rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

ASP Lesson #4 - Session Variables and Cookies


The variables that we have created so far only exist on the page that they are declared. Session variables are the same as normal variables except that they can be used by other pages. Session variables only exist for a certain amount of time which is 10 minutes by default.

Using session variables

You must use the Session object to read and write session variables. Here is an example of how to set the value of a new session variable on one page and how to use it on another page:
page1.asp

Session("MySessionVariable") = Request("txtName")

page2.asp

Response.Write Session("MySessionVariable")

What is a cookie?

Cookies are similar to session variables because they store data that can be used by other pages. The difference is that cookies are stored on the client's computer and session variables are stored on the server. Cookies also last a lot longer that session variables.

Using cookies

The Response.Cookies object is used to create and set the value of a cookie.

Response.Cookies("Name") = "John Smith"

The Request.Cookies object is used to read the value of a cookie.

Response.Write Request.Cookies("Name")

You can also group values under another name such as having first name and last name in the name group.

Response.Cookies("Name")("FirstName") = "John"
Response.Cookies("Name")("LastName") = "Smith"

You can set how long a cookie will be kept on the client's computer before it expires using the 
Expires property of the cookie. You must add the amount of days you want it to last to the current date when you do this.

Response.Cookies("Name") = "John Smith"
Response.Cookies("Name").Expires = Date + 30

ASP Lesson #3 - Control Structures


If Statement

You can make a decision based on user input using an If statement. The If statement tests a condition and if the result is true then it runs the code that follows the If statement but if the result is false then it runs the code after the else statement. Here is an example for when someone enters their age on a form:

Dim Age
Age = Request("txtAge")
if Age >= 18 then
   Response.Write "You are old enough to use this site"
else
   Response.Write "You are too young to use this site"
end if

Select Case Statement

The Select Case statement is similar to the If statement because it also used for making decisions. The difference is that the Select Case statement can have many conditions and the code to run for when the result of each condition is true. Here is an example of choosing a country from a dropdown listbox:

Dim Country
Country = Request("lstCountry")
Select Case Location
Case "USA"
   Response.Write "You are from the USA"
Case "UK"
   Response.Write "You are from the UK"
Case "SA"
   Response.Write "You are from SA"
End Select

For Loop

The For loop is used to loop from one number to another. The code inside the loop is repeated until the second number is reached. Here is an example of counting to 10 using a For loop:

Dim i
for i = 1 to 10
   Response.Write i
next

While Loop

The While loop checks if a condition is true before each time that the code inside the loop is repeated. The loop variable must be set before it is used in a While loop and the loop variable must be incremented inside the loop.
Dim j
j = 1
While j <= 10
   Response.Write j
   j = j + 1
Wend

Do Loop

The Do loop is the same as the While loop except that the condition is tested at the bottom instead of at the top of the loop.

dim k
k = 1
do
   Response.Write k
   k = k + 1
loop until k > 10

ASP Lesson #2 - Forms


An HTML form is a group of text boxes and buttons other things that allow a user to enter data. Here is the form that you see quite often which we will be using:

Username: 
Password: 
Here is the HTML code for the form:

<form method="get" action="showdetails.asp">
Username: <input type="text" name="txtUsername"></input>
Password: <input type="text" name="txtPassword"></input>
<input type="submit" value="Login"></input>
</form>

The method="get" will show the querystring as part of the address in your web browser. The querystring is all the things that come after the ? in an address. Use method="post" to hide the querystring. action=showdetails.asp means that when the Login button is clicked it will go to showdetails.asp where we will process the data from the form.

You can save this form along with all the other code that you need for a basic HTML page as login.htm. The page with the form doesn't have to be an asp page because it doesn't process anything. It is the showdetails.asp page that does all the processing.

Now we will create showdetails.asp. First type the basic code required for an HTML page and then the code that is required for an ASP page. Here is an example:

<% @Language = VBScript %>
<% Option Explicit %>
<html>

<head>
<title>My First ASP Page</title>
</head>

<body>
<%
%>
</body>

</html>

Make sure you save both pages in C:\Inetpub\wwwroot

Requesting form field values

The Request command is used to get the values from the fields of the form. You should first declare variables to store the values that you request. Use the Dim command to declare the variables like this:

Dim Username, Password

If you know Visual Basic then you must remember that you can't choose what data type you want to declare a variable as like you can is Visual Basic.

Next you store the value from the form in the variable using the Request command like this:

Username = Request("txtUsername")
Password = Request("txtPassword")

We must also write the values on the page to make sure it worked using Response.Write.

Response.Write "Your Username is " & Username & "<br>"
Response.Write "Your Password is " & Password

You will see that the & operator has been used to join the string "Your Username is" and the variable Username. You will also see that you can write HTML tags and that they must be between quotes when you it.

Try open http://localhost/login.htm and type something in the form fields and click the login button. Have a look at the result and make sure you understand what we have done.

Functions

There are functions such as the Date function which are built into ASP. Here is an example of how to write the date using the Date function:

Response.Write "The date is " & Date

There are also functions that you can use on data. The Left function for example can be used to get the first letter of the name a person entered.

Dim Name, Surname, Initial
Name = "John"
Surname = "Smith"
Initial = Left(Name, 1)
Response.Write "Hello Mr " & Initial & " " & Surname

There are many more functions available and you can find them on w3schools' list of VBScript functions.

ASP Lesson #1 - Introduction to ASP


This tutorial will teach you how to use ASP(Active Server Pages). It only includes the most important things that you need to know about ASP and leaves out the things that are not used very often. This means that you will learn ASP quicker and not have to go through boring things that you might never use.

Requirements

If you are using Windows 95 or NT 4.0 you need to download and install the Windows NT 4.0 Option Pack.

If you are using Windows 98 then you need to install Personal Webserver from your Windows 98 CD.

If you are using Windows 2000 or XP then you need to install IIS(Internet Information Services) from Control Panel->Add or Remove Programs->Add/Remove Windows Components.

If you don't have any of those then you can get yourself an ASP webhosting account but it is a lot more difficult to learn doing it this way.

You need Microsoft Access if you want to learn about using a database with ASP and you need to know how to use Access.

Other things that you are not required to know but that will help you are:
  • HTML Forms
  • Visual Basic
  • SQL

First ASP Page

We will be creating our ASP pages using Notepad. Open Notepad and type the following code for a basic html page:

<html>

<head>
<title>My First ASP Page</title>
</head>

<body>
</body>

</html>

Now type the following before all the HTML code:

<% @Language = VBScript %>

This tells the webserver that we will be using VBScript as the scripting language in our ASP page. Next you must add the following line straight after the one you have just typed:

<% Option Explicit %>

This tells the webserver that all variables must be declared before they can be used. We will learn about variables later. It is important that you put those 2 lines on all your ASP pages.

All ASP code must be put between an opening <% and a closing %> tag. Your main ASP code should go between the <body> tags.

We will now write the words "Hello World" on our ASP page. The Response.Write command is used to write things. Type the following between the ASP tags:

Response.Write "Hello World"

You can write comments that are ignored by the webserver by typing them after a '. You can write a comment which tells you what the Response.Write to see how it is done. Here is what you should type:

' Writes the words Hello World

Here is what you should have so far:

<% @Language = VBScript %>
<% Option Explicit %>
<html>

<head>
<title>My First ASP Page</title>
</head>

<body>
<%
' Writes the words Hello World
Response.Write "Hello World"
%>
</body>

</html>

Another way to write things is to use just an = in front of what you want to write but you can only do it this way if it is put inside its own set of ASP tags. Here is an example:

<% ="Hello World" %>

You must now save your ASP page. Save it as first.asp in C:\Inetpub\wwwroot. Make sure you choose All Files for the Save as Type. If you don't have a C:\Inetpub\wwwroot folder then you have not installed PWS or IIS. Now open your web browser and go to the http://localhost/first.asp. If you have done everything right then you will see a page that says 
Hello World. Congratulations you have just made your first ASP page.

If you do a View Source on the page that is displayed in your browser you will see that the ASP tags have disappeared. This is because everything between the ASP tags are processed before it is sent to the browser. It is important to understand that the file that the browser receives it not the same ASP file that you created. Don't try editing your ASP file by doing a View Source because it won't work.