Passing An ID with a Hyperlink
For
anyone who's worked with ASP, this article is old hat stuff. But hey,
we're working with newbies here, so don't worry about it. In today's
lesson, we're going to do a couple of things. First we're going to create
a small page that pulls information from a database. Then we'll make
it into a clickable link. The link will pass an ID to a second page
that will pull the remainder of the data based on the ID that was clicked.
So here we go...
First
page is an ASP page. We're going to open our users table and just display
the usernames. Then we will assign the corresponding ID to each username
so when the username is clicked on, it will go to the correct person's
password. Save this first page as pullID.asp.
<%
@Language = VBScript%>
<% Option Explicit %>
<!--#include file="adovbs.inc"-->
<!--#include file="connection.asp"-->
<%
Dim objConn, RS
Notice here
that we did not use the * to select all from our table. In this case
it wouldn't make a lot of difference, but when you know exactly which
fields you are pulling, it's better to pull just those instead of using
the *. The performance is better.
Set RS = objConn.execute("SELECT userID, username FROM users ORDER BY
username")
%>
<html>
<head><title>Display Info</title></head>
<body>
<%
while not rs.eof
Whenever you
use response.write, you must replace double quotes with single quotes
in regular html tags. Notice how we did that in our link tag before
details
response.write "<a href='details.asp?ID="& RS("userID")
& "'>" & RS("username") & "</a><br><hr>"
rs.movenext
wend
rs.close
set rs = nothing
objConn.close
set objConn = nothing
%>
</body></html>
Now
we need to create the page that will display the person's password when
their name is clicked on. Save this page as details.asp.
<%
@Language = VBScript%>
<% Option Explicit %>
<!--#include file="adovbs.inc"-->
<!--#include file="connection.asp"-->
<%
Dim objConn, RS, ID
Because this
ID was not passed through a form, we are not using request.form, but
instead, we will just use request
ID = trim(request("ID"))
Because we
are passing a number instead of a string, we will not need single around
our ID variable
Set RS = objConn.execute("SELECT password FROM users WHERE userID =
" & ID & " ")
%>
<html>
<head><title>Display Info</title></head>
<body>
Your password is <%=RS("password")%>
</body>
</html>
Hopefully
you have a good understanding now of how to pass variables in hyperlinks
to call a record in a second asp page based just on the parameter passed.
If you run into problems getting your pages to work, don't forget to
post your questions on our messageboard. You can download this lesson
and the associated files here. See ya next
time!
~Geoff Swartz |