Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP Programming for the Absolute Beginner

.pdf
Скачиваний:
64
Добавлен:
17.08.2013
Размер:
7.66 Mб
Скачать

156

ASP Programming for the Absolute Beginner

color="#0000FF"><%Response.Write TodayFortune("Fortune_Data")%></font></p> <hr>

<p align="left"><font face="Bookman Old Style" size="3">This is your fortune for

<%=FORMATDATETIME(DATE,vbLongDate)%>. To have another fortune read, click the button

below.</font></p>

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

<p align="center"><input type="submit" value="Tell me another fortune!"

name="B1"></p>

Y

</form>

</body>

</html>

 

If Listing 7.8 seems complicated, don’t fret. It’sLactually very straightforward and builds

on skills you learned in the previous chapters. I’ll go through each section of this code

 

F

one chunk at a time, and you will soon see that this page is quite simple.

 

M

Fortune_Process.asp—Defining the Page Header

Information

A

E

The first section of thisTcode is straightforward HTML. All you are doing is defining the background (in this case, yellow) and giving the page a title:

<html>

<head>

<title>The Clairvoyant Code - Your Fortune is Told!</title> </head>

<body bgcolor="#FFFF00">

Again, very simple. Other than the catchy page title ("The Clairvoyant Code - Your Fortune is Told!"), nothing special is happening in this section of the code.

Fortune_Process.asp—Reading Previous Fortune

Entries

The next section of code scans the Fortune_Track table to determine (based on the username) how many fortunes have already been given to the user. Remember, every time a fortune is presented, information on the fortune seeker is inserted into the Fortune_Track table of the database.

<%

set FortuneTrack=Server.CreateObject("ADODB.Recordset")

FortuneTrack.Open "SELECT * FROM Fortune_Track WHERE Username='" &

Team-Fly®

Request.Form("Name") & "'", "DSN=Fortune"

Dim PrevFortune

PrevFortune = 0

Do While NOT FortuneTrack.EOF

PrevFortune = PrevFortune + FortuneTrack("ID")

FortuneTrack.MoveNext

Loop

FortuneTrack.Close

Set FortuneTrack=nothing

Take a closer look at what’s going on here to understand this critical section of the code:

1.The first part of this section opens a connection to the database. The SELECT statement gathers all records within the Fortune_Track table where the Username field matches the name provided by the user on the Fortune_Info.asp page.

2.The variable PrevFortune is declared and initially set to zero. This variable records how many previous fortunes have been read (and subsequently recorded in the database) for a specific user.

3.Finally, the DO WHILE loop runs through all the return records, as gathered by the SELECT statement. As each record is returned, the values of the Fortune_ID fields are added together. The code will use this number for generating a new fortune.

HINT

In essence, the PrevFortune variable is the sum of all the specific Fortune_ID values

 

 

recorded in the Fortune_Track table. For example, if user Sally Jones has three en-

 

tries in the Fortune_Track table (meaning that she has had her fortune read three

 

times), the PrevFortune adds all the values contained in the Fortune_ID field. Note

 

that the Fortune_ID field corresponds to the ID field of the Fortune_Data table. When

 

a fortune is delivered to a user, the unique identifier of that fortune (the ID field in the

 

Fortune_Data table) is recorded in the Fortune_ID field of the Fortune_Track table.

Fortune_Process.asp—Generating the Magic Number for the New Fortune

The next section of code is where the clairvoyance of the code comes into play. This mystical power is compliments of the RANDOMIZE function within VBScript, as well as the If...Then statement.

MagicNumber = PrevFortune + Request.Form("Age") + Request.Form("Number")

IF MagicNumber > 100 THEN

RANDOMIZE

NewFortune=INT((15 - 1 + 1) * RND + 1)

ELSE

RANDOMIZE

157

C h a p te r

7

E s s en t i a l

P r og r a m m i n g

L o g i P c, a r t

I

158

ASP Programming for the Absolute Beginner

NewFortune=INT((31 - 16 + 1) * RND + 16)

END IF

What’s happening with this section of your code? The MagicNumber variable is used ultimately to pick a new fortune from the Fortune_Data table of the database.

1.The value of the PrevFortune variable (calculated in the first part of your code) is added to the Age and Number values entered by the user on the

Fortune_Info.asp page.

2.The RANDOMIZE function is called to pick a fortune ID (again, corresponding to the ID field of the Fortune_Data table), depending on the ultimate value of the

MagicNumber variable. If the MagicNumber variable is greater than 100, the RANDOMIZE function is called to select a random number between 1 and 15 (including 1 and 15). If the MagicNumber variable is less than 100, the RANDOMIZE function is called to select a random number between 16 and 31 (including 16 and 31). Again, you randomly select a number between 1 and 31 because this range corresponds to the ID field in the Fortune_Data table of the database.

3.This number is assigned to the variable NewFortune, which correlates to a specific ID within the Fortune_Data table.

Fortune_Process.asp—Displaying a New Fortune

After this processing is done, the only thing left to do is display the code. This is done via the following code:

UserName=Request.form("Username")

Set InsertFortune=Server.CreateObject("ADODB.RecordSet")

InsertFortune.Open "INSERT INTO Fortune_Track (Username, Fortune_ID) VALUES

('" & Username & "', " & NewFortune & ")""DSN=Fortune"

set TodayFortune=Server.CreateObject("ADODB.Recordset") TodayFortune.open "SELECT * FROM Fortune_Data WHERE ID=" & NewFortune, "DSN=Fortune"

%>

<p align="left"><font face="Monotype Corsiva" size="6">Thank you, <font color="#0000FF">

<%=Request.Form("Name")%>,</font> wisdom seeker extraordinaire!  Your fortune is as

follows:</font></p>

<hr>

<p align="left"><font size="6" face="Bookman Old Style" color="#0000FF"><%Response.Write TodayFortune("Fortune_Data")%></font></p>

<hr>

<p align="left"><font face="Bookman Old Style" size="3">This is your

fortune for

<%=FORMATDATETIME(DATE,vbLongDate)%>. To have another fortune read, click the button

below.</font></p>

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

<p align="center"><input type="submit" value="Tell me another fortune!" name="B1"></p>

</form>

</body>

</html>

Look at the specific features of this code:

1.After the NewFortune variable is defined (per the preceding section of code), it is inserted into a typical SELECT statement, which reads from the Fortune_Data table.

2.To record which fortune is given to the user, an INSERT statement is used to store the specific fortune ID, the username, and the current data into the Fortune_Track table of the database.

3.Regular HTML formatting (font, color, and so on) is used to present the fortune to the user. Note the use of Response.Write to display the name and the fortune.

4.A typical form (with a submit button labeled Tell me another fortune) is presented. When users click this form, they are returned to the Fortune_Info.asp page, where they can enter information again and have a new fortune read.

Summary

Through the Fortune Teller game, you have learned essential elements of programming ASP pages. You learned how to use the If...Then statement to add programming logic to your code You were introduced to the concept of loops in your code and saw how they greatly reduce the length of your code, as well as add tremendous functionality, especially in looping through records from a database. Building on the material you learned in Chapter 5, “Database Access with ADO,” and Chapter 6, “Using Forms,” you learned how to gather information from a user, integrate it with information being read from a database, and then store the information (via a simple INSERT statement) back into the database. Finally, by using even basic HTML formatting, you learned how to spice up your Web pages, especially when integrating dynamic information read from a database.

159

C h a p te r

7

E s s en t i a l

P r og r a m m i n g

L o g i P c, a r t

I

160

ASP Programming for the Absolute Beginner

E X E R C I S E S

Try these exercises to strengthen your understanding of the concepts presented in this chapter:

1.Although not a specific subject discussed in this chapter, create a new Access database and establish a DSN connection to it. (It never hurts to review this important concept!) Once this is done, create a few simple ASP pages that reference some information in the database, and in turn display it on-screen.

2.Create a Web page that asks the user to enter her age. Then, create another Web page that, utilizing the information provided by the user (you’ll need to be comfortable with forms to work with this exercise), displays one message if the user is under 50 years of age, and another message if the user is over 50 years of age.

3.Similar to exercise #2 above, add a third message. For example, have your page display one message if the user is under 30 years of age; display a second message if he is 31-50 years of age; then, display a third message if he is over 50 years of age.

4.Create a Web page that asks the user to enter some number from one to ten. Then, pass that information to a form “processing” page and, utilizing a Loop, increment by one the number provided by the user. Display these new numbers on-screen, and “loop” (displaying each number for each iteration of the loop) until the loop reaches 50.

5.Develop a Web page that utilizes an If...Then, If...Then...Else and loop. If possible, have the page read/write information to an Access database, too.

C8H A P T E R

Essential

Programming

Logic, Part II

In this chapter, you will

Learn how to use arrays to streamline your programming and to serve as useful containers for a wide range of values within your code.

Work with various VBScript functions, including mathematical, date, and time functions, to add easy functionality to your ASP Web pages.

Develop a game that uses many concepts you’ve learned so far, especially in Chapter 7— including integrating with a database and working with forms.

162

ASP Programming for the Absolute Beginner

In Chapter 7, “Essential Programming Logic, Part I,” you were introduced to fundamental programming concepts within VBScript, including the IF...THEN statement and basic loops. In this chapter, you will build on these essential concepts by learning more about VBScript functionality and, in the process, working more with loops, using arrays, and again integrating your Web pages with a Microsoft database. Finally, especially as you develop the game for this chapter, you will get a preview of more advanced HTML formatting possible with VBScript (you will be learning more about formatting your dynamic VBScript output in Chapter 9, “Formatting Processed Output”).

Introducing Arrays:

Why Do You Need Them?

To describe the concept of an array best, think of—what else—an egg carton. That’s right, an egg carton (because eggs and ASP have so much in common). A typical egg carton has two rows, each containing six slots. If, for some reason, you felt compelled to do so, you could use a felt-tip marker and number the eggs 1 through 12.

Now, before you start defacing eggs in your local supermarket, do a little more visualization. Rather than number the eggs themselves, you number each slot in which the eggs rest. Then you color each egg a different color so that each egg has its own unique color (perhaps it’s Easter time).

You’re probably wondering where I’m going with this (as I am). Seriously, if you can imagine a typical egg carton with 12 uniquely colored eggs, you understand the basic concept of an array. An array is a variable in and of itself. However, unlike a typical variable, an array can store multiple values (usually, values that are related in some way). Consider the code in Listing 8.1.

Listing 8.1 Coding without Arrays

<%

DIM EggCarton(12)

EggCarton(1)="Red"

EggCarton(2)="Blue"

EggCarton(3)="Yellow"

EggCarton(4)="Brown"

EggCarton(5)="Green"

EggCarton(6)="Black"

EggCarton(7)="Gold"

EggCarton(8)="Silver"

EggCarton(9)="Purple"

EggCarton(10)="Orange"

EggCarton(11)="Violet"

EggCarton(12)="White"

%>

The color of the egg in slot 7 is <%=EggCarton(7)%>, but the color of the egg in slot 10 is <%=EggCarton(10)%>.

As you can probably see in Listing 8.1, you are working with an array named EggCarton. This array has 12 slots, each of which corresponds to a specific egg. When the line of code is executed underneath the array, it reads like this:

The color of the egg in slot 7 is Gold, but the color of the egg in slot

10 is Orange.

What’s happening here is that the EggCarton array is used to store the specific, related values (colors) of the 12 eggs. Although this is a simple example, you can already see how, by using arrays, you can easily group together related values for easy reference, retrieval, and manipulation within your code.

Arrays can also be multidimensional. What this means is that you can store more than one piece of information within each slot because within each position are subslots. For example, Listing 8.2 shows the EggCarton array as it would appear were it multidimensional.

Listing 8.2 Defining Elements in an Array

<%

DIM EggCarton(12,1)

EggCarton(0,0)="Egg 1"

EggCarton(0,1)="Red"

EggCarton(1,0)="Egg 2"

EggCarton(1,1)="Blue"

EggCarton(2,0)="Egg 3"

EggCarton(2,1)="Yellow"

EggCarton(3,0)="Egg 4"

EggCarton(3,1)="Brown"

EggCarton(4,0)="Egg 5"

EggCarton(4,1)="Green"

EggCarton(5,0)="Egg 6"

EggCarton(5,1)="Black"

EggCarton(6,0)="Egg 7"

EggCarton(6,1)="Gold"

EggCarton(7,0)="Egg 8"

EggCarton(7,1)="Silver"

EggCarton(8,0)="Egg 9"

EggCarton(8,1)="Purple"

EggCarton(9,0)="Egg 10"

EggCarton(9,1)="Orange"

EggCarton(10,0)="Egg 11"

EggCarton(10,1)="Violet"

EggCarton(11,0)="Egg 12"

EggCarton(11,1)="White"

%>

The egg in slot #4, <%=EggCarton(7,0)%>, has the color <%=EggCarton(7,1)%>

163

C h a p te r

8

E s s en t i a l

P r og r a m m i n g

L o g i P c, ar I t I

164

ASP Programming for the Absolute Beginner

Another way to think of these multidimensional arrays is in terms of a table. Specifically, the first number (or index) in the array corresponds to the row of the table, and the second number (index) is the column.

TRICK

Visualizing arrays as tables is an excellent way of comprehending their layout and

 

 

quickly understanding the values of each position.

Again, you will find that arrays are very useful for grouping together and categorizing related sets of information. Also, because you can dynamically define the values placed into them, they prove to be incredibly powerful tools for storing variable values that are determined as your code executes.

What do I mean by that? If you recall from examples in this book, you can assign values to variables on-the-fly. Consider the example in Listing 8.3.

Listing 8.3 First Array Example

DIM ScoreArray(5)

For i=1 to 5

Value="Score"&i

ScoreArray(i)=Value

Next

When this code executes, the following actions occur:

1.An array by the name of ScoreArray is defined via the DIM statement.

2.A simple For...Next loop is begun. In this instance, the loop runs five times.

3.A variable named Value is set each time the loop executes. The value assigned to this Value variable is dynamically generated: It is a combination of the word Score and the current value of the i variable as it corresponds to the For...Next loop.

Therefore, the first time through the loop, the Value variable has a value equal to

Score1.

4.The Value variable is assigned to a specific position within the ScoreArray. Again, because this is dynamic code, the first time through the loop, the code executes as

ScoreArray(1)="Score" (as the current value of i is evaluated).

Zero-Based Arrays

Zero-based indicates that all arrays have one more element than it would appear. In the array SomeArray(7), there are actually eight elements because the array is zero-based. Basically, this means that the zero position is a viable position for storing data within the variable, so the SomeArray(7) variable can have its elements defined as in Listing 8.4.

Listing 8.4 Example of Zero-Based Arrays

SomeArray(0)="Los Angeles"

SomeArray(1)="Boston"

SomeArray(2)="Chicago"

SomeArray(3)="Dallas"

SomeArray(4)="Denver"

SomeArray(5)="Indianapolis"

SomeArray(6)="Houston"

SomeArray(7)="New York"

As you can see, there are eight elements in the SomeArray(7) array, because of the existence of the zero position. Don’t let this confuse you. Just remember that you always have that extra element (the zero position) to work with.

TRAP

Remember not to exceed the maximum number of elements within an array. In the SomeArray example, if you tried to assign a value to element SomeArray(8), you would receive an error. Even though there are eight elements in this array, the zero element counts as the first position, so the highest element number is still 7.

Useful Array Functions

VBScript presents many useful functions for working with arrays. In this section, I will describe a few of these and show how you can use them to your advantage within your ASP Web pages.

UBOUND()

The first function, UBOUND(), allows you to retrieve the size of an array quickly. For example, take a look at Listing 8.5.

Listing 8.5 Example of UBOUND() Function

DIM JohnArray(23, 34)

UBOUND(JohnArray)

UBOUND(JohnArray, 1)

UBOUND(JohnArray, 2)

What is displayed when this code executes? Each UBOUND() function call returns a unique value:

1. UBOUND(JohnArray) returns the value of 23. Why 23 and not 34 (or some other answer)? If you just place the array name within the UBOUND function, it automatically returns the highest value of the array’s first dimension. In this case, the highest value possible in the first dimension is 23.

TRICK

Don’t let all this talk of multidimensional arrays throw you. Think of a table, and

 

 

visualize rows and columns so that you can see the different dimensions of the ar-

 

ray and the values they contain.

2.In UBOUND(JohnArray, 1), the value of 23 is again returned. You are specifically asking for the upper limit of the first dimension of the array, which is 23.

3.In UBOUND(JohnArray, 2), the value of 34 is returned. You are asking for the upper limit of the second dimension to be returned, which is 34.

165

C h a p te r

8

E s s en t i a l

P r og r a m m i n g

L o g i P c, ar I t I