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
Response.Write "<select name=""dept"">"
Do While Not rs.EOF
dept = Server.HTMLEncode(CStr(rs("dept")))
Response.Write "<option value=""" & dept & """>" & dept & "</option>"
rs.MoveNext
Loop
Response.Write "</select>"The example assumes rs contains department names. It HTML-encodes the values before placing them in attributes and text; see the complete ADO example below.
This legacy Access-backed example shows the general ADO pattern for building a dropdown from database rows. The same SELECT/loop/output pattern applies when the data source is moved to a supported server database. The query selects each department once with DISTINCT, then writes one HTML <option> for each row.
Response.Write "<select name=""dept"">"
Response.Write "<option value="""">Departments</option>"
Do While Not objRS.EOF
deptText = Server.HTMLEncode(CStr(objRS("dept")))
Response.Write "<option value=""" & deptText & """>" & deptText & "</option>"
objRS.MoveNext
Loop
Response.Write "</select>"
<%@ Language="VBScript" %>
<% Option Explicit %>
<!-- #include virtual="/adovbs.inc" -->
<%
Dim objconn, objRS, strSQL, deptText
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 DISTINCT dept FROM emp_m ORDER BY dept"
objRS.Open strSQL, objconn
Response.Write "<select name=""dept"">"
Response.Write "<option value="""">Departments</option>"
Do While Not objRS.EOF
deptText = Server.HTMLEncode(CStr(objRS("dept")))
Response.Write "<option value=""" & deptText & """>" & deptText & "</option>"
objRS.MoveNext
Loop
Response.Write "</select>"
objRS.Close
Set objRS = Nothing
objconn.Close
Set objconn = Nothing
%>
The displayed/attribute value is HTML-encoded before being written. If an option value must later be used in a query, validate it and pass it as a database parameter rather than concatenating it into SQL.
Encode both the option value and visible label. If you need to retain the selection, compare the submitted value with the current row value and add a selected attribute only when they match.
The next lesson, dependent dropdowns, uses a department choice to load a matching employee list while keeping SQL parameters separate from user input.
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.