Use this example to see the core idea, then work through the complete steps below. Code snippets are Classic ASP / VBScript or SQL Server T-SQL as labelled, not PHP.
VBScript example
Set rs = cn.Execute("SELECT emp_no, name FROM emp_m ORDER BY emp_no")
Do While Not rs.EOF
Response.Write Server.HTMLEncode(CStr(rs("name"))) & "<br>"
rs.MoveNext
Loop
rs.CloseHere cn is an open ADO connection (see the Access connection lesson). Encode database text before inserting it into HTML.
This page keeps the original Access/ADO example for legacy-maintenance learning. For a new server-side application, prefer a server database such as SQL Server. If you are maintaining an existing Access-backed ASP site, loop through the returned Recordset until EOF becomes true and encode values before sending them to HTML.
Set objconn = Server.CreateObject("ADODB.Connection")
objconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Server.MapPath("db/emp.mdb")
objconn.Open
strSQL = "SELECT emp_no, name FROM emp_m ORDER BY emp_no"
Response.Write Server.HTMLEncode(CStr(objRS("emp_no"))) & " " & _
Server.HTMLEncode(CStr(objRS("name"))) & "<br>"
145 John Reid
245 Peter Horn
175 Rabin Pack
187 Ran Keth
Dim objconn, objRS, strSQL
Set objconn = Server.CreateObject("ADODB.Connection")
objconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Server.MapPath("db/emp.mdb")
objconn.Open
Set objRS = Server.CreateObject("ADODB.Recordset")
strSQL = "SELECT emp_no, name FROM emp_m ORDER BY emp_no"
objRS.Open strSQL, objconn
Do While Not objRS.EOF
Response.Write Server.HTMLEncode(CStr(objRS("emp_no"))) & " " & _
Server.HTMLEncode(CStr(objRS("name"))) & "<br>"
objRS.MoveNext
Loop
objRS.Close
Set objRS = Nothing
objconn.Close
Set objconn = Nothing
Server.HTMLEncode() is used here because database content can still contain characters that should not be interpreted as HTML.
Before reading a field, test rs.EOF. For lists, a Do While Not rs.EOF loop naturally skips the body when no rows match. Do not rely on RecordCount for forward-only cursors.
Always HTML-encode database-supplied text before rendering it into the response, including names and other fields that may have originated as form input. See displaying SQL Server rows for the equivalent workflow.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.