|
|
|
|
Selecting a random record
Download the code
The code below accesses an Access database called 'Friends.mdb'
with a table 'tblFriends'. The table has 3 fields firstly an 'ID'
field that is an autonumber, secondly a field called 'FirstName'
which is a textfield and lastly another textfield called 'SurName'.
Our code will select a random record from our table and loop through
all the recordset fields printing out the values.
You will notice that the code below doesn't expressly retrieve
these fields, rather it uses generic code that will retrieve the
recordset fields and values from any database and table structure.
Call our file 'random_record.asp'.
<%@ Language="VBScript" %>
<% Option Explicit %>
<html>
<head>
<title>Selecting a random record</title>
</head>
<body>
<%
dim connection, recordset, sConnString, sql
dim intRandomNumber, intTotalRecords, i
sql = "SELECT * FROM tblFriends"
Set connection = Server.CreateObject("ADODB.Connection")
Set recordset = Server.CreateObject("ADODB.Recordset")
sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;"
& _
"Data Source=" & Server.MapPath("Friends.mdb")
connection.Open(sConnString)
recordset.Open sql, connection, 3, 1
intTotalRecords = recordset.RecordCount
Randomize()
intRandomNumber = Int(intTotalRecords * Rnd)
recordset.Move intRandomNumber
Response.write("<table border='1'><tr>")
For i = 0 to recordset.Fields.Count - 1
Response.write("<td>" & recordset(i) &
"</td>")
Next
response.write("</tr></table>")
recordset.Close
Set recordset=Nothing
connection.close
Set connection=Nothing
%>
</body>
</html>
Site developed by Michael Wall - Web Design Belfast N.Ireland.
Copyright © 2000-2008. All rights reserved.
|
|
|
|
|