JavaScript Basics: Loops, Dates, and Functions
JavaScript Basics: Loops, Dates, and Functions
4th class
Dr. Athraa Jasim Mohammed
1
parseInt() or parseFloat()
for loop
for/in a loop (explained later)
while loop
do…while loop
2
For loop
Syntax:
<script type="text/javascript">
[Link]("<b>Using for loops </b><br />");
for (var i=0;i<9;i++)
{
[Link](“*” + "<br />");
}
</script>
While loop
Syntax:
while(condition)
{
lines of code to be executed
}
3
<script type="text/javascript">
[Link]("<b>Using while loops </b><br />");
var i = 0, j = 1, k;
[Link](" series less than 40<br />");
while(i<40)
{
[Link](i + "<br />");
k = i+j;
i = j;
j = k;
}
</script>
do…while loop
Syntax:
do
{ block of code to be executed
} while (condition)
The do…while loop is very similar to while loop. The only difference is
that in do…while loop, the block of code gets executed once even before
checking the condition
4
Dynamic Web programming
Create a Date Object
Objects and arrays (which are a specific kind of object) provide ways to
group several values into a single value. Conceptually, this allows us to
put a bunch of related things in a bag and run around with the bag,
instead of wrapping our arms around all of the individual things and
trying to hold on to them separately.
The Date object is used to work with dates and times. Date objects are
created with the Date() constructor.
in the following example we set a Date object to be 5 days into the future:
Note: If adding five days to a date shifts the month or year, the changes
are handled automatically by the Date object itself!
5
Compare Two Dates
The Date object is also used to compare two dates. The following
example compares today's date with the 14th January 2010:
Where get is used to retrieve a specific component from a date, set is used
to modify components of a date.
6
or four digit number
random()
The [Link]() function is used to return a floating-point random
number between range [0,1) , 0 (inclusive) and 1 (exclusive).This random
number can then be scaled according to the desired range
[Link]([Link]([Link]()*10));
max()
use max() to return the number with the highest value of two specified
numbers.
min()
use min() to return the number with the lowest value of two specified
numbers.
7
var b = 'I am a JavaScript hacker.'
[Link]([Link](5))
Split
split() is a specialized method that you need sometimes. It allows you to
split a string at the places of a certain character. You must put the result
in an array, not in a simple variable.
Now the string has been split into 5 strings that are placed in the array
temp. The spaces themselves are gone.
temp[0] = 'I';
temp[1] = 'am';
temp[2] = 'a';
temp[3] = 'JavaScript';
temp[4] = 'hacker.';
<script type="text/javascript">
var myRegExp = /Alex/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = [Link](myRegExp);
8
if(matchPos1 != -1)
[Link]("There was a match at position " + matchPos1);
else
[Link]("There was no match in the first string");
</script>
9
Dynamic Web programming
4th class
Dr. Athraa Jasim Mohammed
The second course
Second Lecture
2021-2022
1
JavaScript Functions
A function is a piece of program wrapped in a value. Such values can be
applied in order to run the wrapper program. For example, in a browser
environment, the binding prompt holds a function that shows a little
dialog box asking for user input. It is used like this:
Functions can be defined both in the <head> and in the <body> section
of a document. However, to assure that a function is read/loaded by the
browser before it is called, it could be wise to put functions in the <head>
section.
Syntax
function function-name(var1,var2,...,varX)
{
some code
}
The parameters var1, var2, etc. are variables or values passed into the
function. The {and the} defines the start and end of the function.
2
Note:
Example
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!"); }
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
3
Example
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
[Link](product(4,3));
</script></body> </html>
If you declare a variable outside a function, all the functions on your page
can access it. The lifetime of these variables starts when they are <html>
Example
<head>
<script type="text/javascript">
Function myfunction(txt)
{ alert(txt);}
</script> </head> <body>
<form>
<input type="button" onclick="myfunction('Hello')" value="Call
function">
</form>
<p>By pressing the button above, a function will be called with "Hello"
as a parameter. The function will alert the parameter.</p>
</body> </html>
4
The HTML specification refers to these as intrinsic events and defines 18
as listed below:
Event Handler Event that it handles
onChange User has changed the object, then attempts to leave that field (i.e.
clicks elsewhere).
onClick User clicked on the object.
onDblClick User clicked twice on the object.
onKeydown A key was pressed over an element.
onKeyup A key was released over an element.
onKeypress A key was pressed over an element then released.
onLoad The object has loaded.
onMousedown The cursor moved over the object and mouse/pointing device was
pressed down.
onMouseup The mouse/pointing device was released after being pressed down.
onMouseover The cursor moved over the object (i.e. user hovers the mouse over
the object).
onMousemove The cursor moved while hovering over an object.
onMouseout The cursor moved off the object
onReset User has reset a form.
onSelect User selected some or all of the contents of the object. For
example, the user selected some text within a text field.
onSubmit User submitted a form.
onUnload User left the window (i.e. user closes the browser window).
5
Dynamic Web programming
Array
JavaScript provides a data type specifically for storing sequences
of values. It is called an array and is written as a list of values between
square brackets, separated by commas. An array is a special variable,
which can hold more than one value, at a time. If you have a list of items
(a list of car names, for example), storing the cars in single variables
could look like this:
2- cars1="Saab";
cars2="Volvo";
cars3="BMW";
However, what if you want to loop through the cars and find a specific
one? And what if you had not 3 cars, but 300?
The best solution here is to use an array! An array can hold all your
variable values under a single name. And you can access the values by
referring to the array name. Each element in the array has its own ID so
that it can be easily accessed.
Create an Array
1:
2:
3:
6
Note: If you specify numbers or true/false values inside the array then the
variable type will be Number or Boolean, instead of String.
Access an Array
[Link](myCars[0]);
will result in the following output: Saab
To modify a value in an existing array, just add a new value to the array
with a specified index number:
myCars[0]="Opel";
[Link](myCars[0]);
will result in the following output: Opel
Arrays - concat()
var parents = ["Jani", "Tove"];
var children = ["Cecilie", "Lone"];
var family = [Link](children);
[Link](family);
The backslash (\) is used to insert apostrophes, new lines, quotes, and
other special characters into a text string.
To solve this problem, you must place a backslash (\) before each double
quote in "Viking". This turns each double quote into a string literal:
7
var txt="We are the so-called \"Vikings\" from the north.";
[Link](txt);
JavaScript will now output the proper text string: We are the so-called
"Vikings" from the north.
The table below lists other special characters that can be added to a text
string with the backslash sign:
Code Outputs
\' single quote
\" Double quote
\& Ampersand
\\ Backslash
\n new line
\b Backspace
String
We can read properties like length and toUpperCase from string values.
2- Style strings
8
3- The toLowerCase() and toUpperCase() methods
[Link]([Link]());
[Link]([Link]("Microsoft"," Schools"));
[Link]([Link]("world")); //6
9
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
Document.
11
Dynamic Web programming
4th class
Dr. Athraa Jasim Mohammed
The second course
Third Lecture
2021-2022
1
JavaScript Form Validation
There's nothing more troublesome than receiving orders, guestbook
entries, or other form submitted data that are incomplete in some way.
You can avoid these headaches once and for all with JavaScript's amazing
way to combat bad form data with a technique called "form validation".
JavaScript [Link]
JavaScript getElementById
There's an easy way to access any HTML element, and it's through the
use of id attributes and the getElementById function.
If you want to quickly access the value of an HTML input give it an id to
make your life easier. This small script below will check to see if there is
any text in the text field "myText". The argument that getElementById
requires is the id of the HTML element you wish to utilize.
<script type="text/javascript">
function notEmpty(){
var myTextField = [Link]('myText');
if([Link] != "")
alert("You entered: " + [Link])
else
alert("Would you please enter some text?")
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />
JavaScript Code:
// If the element's string matches the regular expression it is all
numbers.
var numericExpression = /^[0-9]+$/;
2
Inside each string is a function called a match that you can use to see if
the string matches a certain regular expression. We accessed this function
like so: [Link](expression here).
This function will be identical to isNumeric except for the change to the
regular expression we use inside the match function. Instead of checking
for numbers we will want to check for all letters.
If we wanted to see if a string contained only letters we need to specify an
expression that allows for both lowercase and uppercase letters:
/^[a-zA-Z]+$/ .
JavaScript Code:
// If the element's string matches the regular expression it is all letters
3
Form Validation - Restricting the Length
Being able to restrict the number of characters a user can enter into a field
is one of the best ways to prevent bad data. For example, if you know that
the zip code field should only be 5 numbers you know that 2 numbers is
not sufficient.
Below we have created a lengthRestriction function that takes a text field
and two numbers. The first number is the minimum number of characters
and the second is the maximum number of a characters the input can be.
If you just want to specify an exact number then send the same number
for both minimum and maximum.
JavaScript Code:
function lengthRestriction(elem, min, max){
var uInput = [Link];
if([Link] >= min && [Link] <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ "
characters");
[Link]();
return false;
}
}
And for our grand finale we will be showing you how to check to see if a
user's email address is valid. Every email is made up for 5 parts:
A combination of letters, numbers, periods, hyphens, plus signs, and/or
underscores The at symbol @ A combination of letters, numbers,
hyphens, and/or periods A period The top level domain (com, net, org, us,
gov, ...)
.
Valid Examples:
[Link]@[Link]
jack+jill@[Link]
the-stand@[Link]
Invalid Examples:
@[Link] - no characters before the @
free!dom@[Link] - invalid character !
shoes@need_shining.com - underscores are not allowed in the domain
name
4
The innerHTML
[Link]('{ID of
element}').innerHTML = '{content}';
Code:
<html>
<head>
<script type="text/javascript">
function Msg1(){
[Link]('myText').innerHTML = 'Thanks!';
}
function Msg2(){
[Link]('myText').innerHTML = 'Try message 1
again...';}
</script>
</head>
<body><form>
<input type="button" onclick="Msg1()" value="Show Message 1" />
<input type="button" onclick="Msg2()" value="Show Message 2" />
5
<p id="myText"></p>
</form>
</body>
</html>
Result:
Thanks!
This code includes two functions and two buttons. Each function displays
a different message and each button triggers a different function. In the
functions, the getElementById refers to the HTML element by using
its ID. We give the HTML element an ID of "myText" using
id="myText".
[Link]('myText').innerHTML = 'Thanks!';
When you write a JavaScript function, you will need to determine when it
will run. Often, this will be when a user does something like a click or
hover over something, submit a form, double clicks on something etc.
Using JavaScript, you can respond to an event using event handlers. You
can attach an event handler to the HTML element for which you want to
respond to when a specific event occurs.
6
Code:
<script type="text/javascript">
function showMsg(){
var userInput = [Link]('userInput').value;
[Link]('userMsg').innerHTML = userInput;
}
</script>
<input type="text" maxlength="40" id="userInput"
onkeyup="showMsg()" value="Enter text here..." />
<p id="userMsg"></p>
Result:
Code:
<script type="text/javascript">
function changeColor(){
var newColor = [Link]('colorPicker').value;
[Link]('colorMsg').[Link] = newColor;
}
</script>
<p id="colorMsg">Choose a color...</p>
<select id="colorPicker" onchange="JavaScript:changeColor()">
<option value="#000000">Black</option>
<option value="#000099">Blue</option>
<option value="#990000">Red</option>
<option value="#009900">Green</option>
</select>
Result:
Choose a color...
Sometimes, you may need to call some JavaScript from within a link.
Normally, when you click a link, the browser loads a new page (or
refreshes the same page). This might not always be desirable. For
example, you might only want to dynamically update a form field when
the user clicks a link.
7
Example: JavaScript "On Double Click"
You could just have easily used another event to trigger the same
JavaScript. For example, you could run JavaScript only when the double
clicks the HTML element. We can do this using the onDblClick event
handler.
Code:
<input type="button" onDblClick="alert('Hey, remember to tell your
friends about [Link]!');" value="Double Click Me!" />
To prevent the load from refreshing, you could use the JavaScript void()
function and pass a parameter of (zero).
Code:
<a href="JavaScript:void(0);"
ondblclick="alert('Well done!')">Double Click
Me!</a>
Result:
Double Click Me!
Code:
Result:
Double Click Me!
8
Did you notice the page refresh as soon you clicked the link. Even if you
double clicked and triggered the "ondbclick" event, the page still reloads!
This code can be called automatically upon an event or simply when the
user clicks on a link.
code:
You can use JavaScript to automatically open print dialogue box so that
users can print the page. Although most users know they can do
something like "File > Print", a "Print this page" option can be nice, and
may even encourage users to print the page. Also, this code can be
triggered automatically upon loading a printer friendly version.
The following code creates a hyperlink and uses the Javascript print
function to print the current page:
9
Dynamic Web programming
4th class
Dr. Athraa Jasim Mohammed
The second course
Fourth Lecture
2021-2022
1
Open a new window in JavaScript
One of the more common requests I see is how to open a new Javascript
window with a certain feature/argument. The [Link] method has
been available since Netscape 2.0 (Javascript 1.0), but additional window
decoration features have been added to the syntax since then.
[Link] method
The syntax to open a popup is:
[Link](url, name, params)
url
An URL to load into the new window.
name
A name of the new window. Each window has a [Link], and
here we can specify which window to use for the popup. If there’s
already a window with such name – the given URL opens in it,
otherwise a new window is opened.
params
The configuration string for the new window. It contains settings,
delimited by a comma. There must be no spaces in params, for
instance: width=200,height=100.
2
Write to a new window
How do I write script-generated content to another window?
To write script-generated content to another window, use the method
[Link](), as returned by the [Link]()
method.
To make sure that your script's output actually shows up in the other
window, use [Link]() after writing the content.
As an example, consider the following function that opens a new window
with the title Console and writes the specified content to the new
Examples
<HTML>
<HEAD>
<TITLE>Writing to Subwindow</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var newWindow
function makeNewWindow() {
newWindow = [Link]("","","status,height=200,width=300")
}
function subWrite() {
if ([Link]) {
makeNewWindow()
}
[Link]()
var newContent = "<HTML><HEAD><TITLE>A New Doc</TITLE></HEAD>"
newContent += "<BODY BGCOLOR='coral'><H1>This document is brand new.</H
1>"
newContent += "</BODY></HTML>"
[Link](newContent)
[Link]() // close layout stream
}
</SCRIPT>
</HEAD>
<BODY onLoad="makeNewWindow()">
<FORM>
<INPUT TYPE="button" VALUE="Write to Subwindow" onClick="subWrite()">
</FORM>
</BODY>
</HTML>
3
Moving and resizing windows
When you have created a window, you can use Javascript to move it or
resize it.
Moving windows
A window object has two methods for moving it: moveTo and moveBy.
Both take two numbers as arguments.
The first function moves the window to the specified coordinates, measured
in pixels from the top left corner of the screen. The first argument is the
horizontal, or X, coordinat, and the second is the vertical, or Y, coordinate.
[Link](x, y)
x is the horizontal coordinate to be moved to.
y is the vertical coordinate to be moved to.
Example
<script type="text/javascript">
function open_and_move1(){
win2=[Link]("[Link]","","width=300,height=300")
[Link](0,0)
}
</script
The second method changes the current coordinates by the given amounts,
which can be negative to move the window left or up.
Not all browsers allow you to move a window.
[Link](deltaX, deltaY)
Example
<script type="text/javascript">
function open_and_move2(){
win3=[Link]("[Link]","","width=600,height=500")
[Link]([Link]/2-300,[Link]/2-250)
}
</script>
The center coordinates of the screen in the second example is calculated by
determining the screen's dimensions, dividing that by 2, and subtracting half
of either the window's width/height from it. In other words, in order to
center a window,
4
Resizing windows
Similar to the methods for moving, there are two methods for resizing a
window: resizeTo and resizeBy. Like for moving, they either set the
size absolutely or modify the size relatively to the current size.
Most browsers' standard security setting will not let you resize a window to
less than 100 pixels in any direction.
[Link] (100,-100);
Closing windows
[Link]();
External JavaScript
You can place all your scripts into an external file (with a .js extension),
then link to that file from within your HTML document. This is handy if
you need to use the same scripts across multiple HTML pages, or a whole
website.
To link to an external JavaScript file, you add a src attribute to your
HTML script tag and specify the location of the external JavaScript file.
5
external file! Let’s create an external JavaScript file that prints Hello
Javatpoint in a alert dialog box.
[Link]
function msg(){
alert("Hello Javatpoint");
}
Let’s include the JavaScript file into html page. It calls the JavaScript function
on button click.
[Link]
<html>
<head>
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
6
Active Server Pages or Classic ASP
Introduction
26
What is ASP?
ASP is a powerful tool for making dynamic and interactive Web pages.
After you have installed IIS, make sure you install all patches for bugs
and security problems. (Run Windows Update).
27
Steps Install IIS on Windows 7 and Windows Vista
There are two different types of (Script Languages) can be used to write
the active code on the ASP pages are:
1 - VBScript (the default language permitted use in the pages of the
ASP).
<%@ language= "VBscript" %>
2 - JavaScript.
<%@ language= "Javascript" %>
An ASP file normally contains HTML tags, just like an HTML file.
However, an ASP file can also contain server scripts, surrounded by the
delimiters <% and %>.
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.
What is localhost
Let us first see, what we mean by a hostname. Whenever you
connect to a remote computer using it’s URL, you are in effect calling it
by its hostname.
28
For example, when you type in [Link] you are really
asking the network to connect to a computer named
[Link]. 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 (which is what you wanted to do anyway.)
For testing all your pages, you will need to use localhost as the hostname.
When executing programs for the server, write hostname and the name of
the program :- [Link]
ASP Objects
1-Response Object
The ASP Response object is used to send output to the user from the
server. Its collections, properties, and methods are described below:
Methods
Method Description
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Redirect Redirects the user to a different URL
Write Writes a specified string to the output
29
Write method
The Write method writes a specified string to the output.
Syntax
[Link] (variant )
Parameter Description
variant Required. The data to write
<%
[Link]("Hello World!")
%>
Variable in asp
A variable is used to store information. Dim variable
<%
dim i
for i=1 to 6
[Link]("<h" & i & ">Heading " & i & "</h" & i & ">")
next
%>
Redirect Method
The Redirect method redirects the user to a different URL.
Syntax
[Link] URL
Parameter Description
URL Required. The URL that the user (browser) is redirected to
Examples
<%
[Link] [Link] %>
30
Request object
When a browser asks for a page from a server, it is called a request. The
Request object is used to get information from a visitor. Its collections,
properties, and methods are described below:
Collections
Collection Description
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that
uses the post method
QueryString Contains all the variable values in a HTTP query string
Used to deliver data sent by the user's computer to a server through HTTP
request.
Required object
There are two ways to get form information:
1- The [Link] command
2- The [Link] command.
1- [Link]
The [Link] command collects the values in a form as
text. Information sent from a form with the GET method is visible to
everybody (in the address field). Remember that the GET method limits
the amount of information to send.
[Link]
Method="get‖
action = ―[Link]"
Syntax
[Link](variable)[(index)|.Count]
[Link]
Command [Link], which is not much different from something
[Link], it is used to gather the values of the form with
the use of method Post, which may not be visible to anyone, and it
does not specify the amount of.
31
Syntax
[Link](element)[(index)|.Count]
[Link]
Method=―post‖
action = ―[Link]"
32
<input type="submit" value=―sent data‖ >
</form>
</body>
</html>
Run
[Link] &lname=Habeeb
Example3
[Link]
<html>
<body>
<form method="get" action="[Link]">
fname: <input type="text" name="fname">
</br >
lname: <input type="text" name="lname">
</br ></br >
<input type="submit" value=―send data">
</form>
</body>
</html>
33
[Link]
<html>
<body>
<%
dim fname,lname
fname=[Link]("fname―)
lname=[Link]("lname―)
%>
<%=―fname<B>"&fname&"</b>"%>
<%=―lname<B>"&lname &"</B>"%>
</body>
</html>
Login Application:
Login Application: is used to allow the authorized users to access private
and secured areas(web pages), by using User-Name and Password strings.
34
However, the internal pages ('ok. asp' and 'in .asp' pages) must be having
"Guarding Code" to prevent any direct access to them. So if any user
writes the following address (HTTP:// ......... / ok. asp) to access the 'ok.
Asp' page without coming from login-form (in another word to
bypassing the checking code), the guarding-code must prevent this
unauthorized access and the process must be returned to the 'default, asp'
page The "Guarding Code" must be written inside all internal pages.
Guarding-Code is work by check if the user access to this page by
follows authorized-path or not. If the user access '[Link]' page and
enter the correct username and password strings, then the '[Link]' the
page must not only redirect the process to the '[Link]' page but must
register the username inside cookie file. So when access the '[Link]' page
the process must be check cookies file, if cookie hold username then this
means that the user access '[Link]' page by follow the authorized path,
35
else if cookie hold nothing then this means that the user tries to access to
the '[Link]' page by by-passing checking code.
Cookies
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With ASP,
you can both create and retrieve cookie values.
<%
[Link]("firstname")="Alex"
%>
It is also possible to assign properties to a cookie, like setting a date when
the cookie should expire:
<%
[Link]("firstname")="Alex"
[Link]("firstname").Expires=#May 10,2012#
%>
36
[Link]("user")("country")="Norway"
[Link]("user")("age")="25"
%>
However, when user wants to leave '[Link]' page, so the user must be sign
out this page, this means that the user must put nothing inside cookie file.
FileSystemObject
The FileSystemObject object is used to access the file system on a server.
This object can manipulate files, folders, and directory paths. It is also
possible to retrieve file system information with this object.
[Link]
Set fs = CreateObject("[Link]")
Set a = [Link]("c:\[Link]", True)
[Link]("This is a test.")
[Link]
<%
Set fs = CreateObject("[Link]")
Set wfile = [Link]("c:\Mydir\[Link]")
filecontent = [Link]
[Link]
Set wfile=nothing
Set fs=nothing
[Link](filecontent)
%>
37
ReadLine
<%
Set fs = CreateObject("[Link]")
Set wfile = [Link]("c:\Mydir\[Link]")
firstname = [Link]
lastname = [Link]
theage = [Link]
[Link]
Set wfile=nothing
Set fs=nothing
%>
Your first name is <% =firstname %><BR>
Your last name is <% =lastname %><BR>
Your are <% =thaage %> years old<BR>
AtEndOfStream
<%
Set fs = CreateObject("[Link]")
Set wfile = [Link]("c:\Mydir\[Link]")
counter=0
do while not [Link]
counter=counter+1
singleline=[Link]
[Link] (counter & singleline & "<br>")
loop
[Link]
Set wfile=nothing
Set fs=nothing
%>
38
ADO (ActiveX Data Objects)
39
Create a DSN-less Database Connection
The easiest way to connect to a database is to use a DSN-less connection.
A DSN-less connection can be used against any Microsoft Access
database on your web site.
If you have a database called "[Link]" located in a web directory
like "c:/webdata/", you can connect to the database with the following
ASP code:
<%
set conn=[Link]("[Link]")
[Link]="[Link].4.0"
[Link] "c:/webdata/[Link]"
%>
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.
ADO Recordset
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).
To be able to read database data, the data must first be loaded into a
recordset.
Suppose we have a database named "Northwind", we can get access to
the "Customers" table inside the database with the following lines:
set objRecordset=[Link]("[Link]")
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.
40
databases of all shapes and sizes and is used as the basis for all user and
administrator interactions with the database.
Examples The SELECT command retrieves data from one or more tables
or views. It generally consists of the following language elements:
SELECT <things_to_be_displayed> -- called 'Projection' - mostly a list of columns
FROM <tablename> -- table or view names and their aliases
WHERE <where_clause> -- the so called 'Restriction' or 'search condition'
ORDER BY <order_by_clause>
FETCH <fetch_first_or_next_clause>;
<%
set conn=[Link]("[Link]")
[Link]="[Link].4.0"
[Link] "c:/webdata/[Link]"
set rs = [Link]("[Link]")
[Link] "SELECT * FROM Customers", conn
do until [Link]
for each x in [Link]
[Link]([Link])
[Link](" = ")
[Link]([Link] & "<br>")
next
[Link]("<br>")
[Link]
loop
[Link]
[Link]
%>
Display Selected Data
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):
<%
set conn=[Link]("[Link]")
[Link]="[Link].4.0"
41
[Link] "c:/webdata/[Link]"
set rs=[Link]("[Link]")
sql="SELECT Companyname, Contactname FROM Customers
WHERE CompanyName LIKE 'A%'"
[Link] sql, conn
%>
set rs = [Link]("[Link]")
sql="SELECT Companyname, Contactname FROM
Customers ORDER BY CompanyName"
[Link] sql, conn
%>
<table border="1" width="100%">
<tr>
<%for each x in [Link]
[Link]("<th>" & [Link] & "</th>")
42
next%>
</tr>
<%do until [Link]%>
<tr>
<%for each x in [Link]%>
<td><%[Link]([Link])%></td>
<%next
[Link]%>
</tr>
<%loop
[Link]
[Link]%>
</table>
</body>
</html>
<html>
<body>
43
<td><input name="country"></td>
</tr>
</table>
<br><br>
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>
</body>
</html>
<html>
<body>
<%
set conn=[Link]("[Link]")
[Link]="[Link].4.0"
[Link] "c:/webdata/[Link]"
44