Displaying all Records from a Database in ASP

Download the code

The code below will simply display all the records from our "tblFriends" table in the database called 'Friends.mdb'. The table has 3 columns, firstly an 'ID' field that is an autonumber, secondly a field called 'FirstName' which is a textfield and lastly another textfield called 'SurName'.

Call our file 'display_records.asp'

<%@ Language="VBScript" %>
<% Option Explicit %>
<html>
<head>
<title>Displaying all records from a database table</title>
</head>
<body>
<%
'declare your variables
Dim Connection, Recordset
Dim sSQL, sConnString

'declare SQL statement that will query the database
sSQL="SELECT * FROM tblFriends"

'define the connection string, specify database
'driver and the location of database
sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("Friends.mdb")


'create an ADO connection and recordset
Set connection = Server.CreateObject("ADODB.Connection")
Set recordset = Server.CreateObject("ADODB.Recordset")

'Open the connection to the database
connection.Open sConnString

'Open the recordset object, execute the SQL statement
recordset.Open sSQL,connection

'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'If there are records then loop through the fields
Do While Not recordset.EOF
Response.Write recordset("ID") & " " & recordset("FirstName") & " " & _
recordset("SurName")
Response.Write "<br>"  'insert a line break
'move on to the next record
Recordset.MoveNext
Loop
End If

'close the connection and recordset objects and free up resources
Recordset.Close
Connection.Close
Set Recordset = Nothing
Set Connection = Nothing
%>
</body>
</html>

The above code will display the ID number, the FirstName and SurName of all the entries in your database table. If there are no entries then the message 'No records returned.' will be displayed.

Previous: INSERT Records

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Get your best asp web hosting provider now and save 25%