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 cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
cmd.CommandType = 1 ' adCmdText
cmd.CommandText = "SELECT emp_no, name FROM emp_m WHERE emp_no = ?"
cmd.Parameters.Append cmd.CreateParameter("pEmp", 3, 1, , 145)
Set rs = cmd.Execute
If rs.EOF Then Response.Write "No matching record"This example assumes an open SQL Server ADO connection cn. Bind an integer with adInteger = 3; never concatenate visitor input into query text.
To test whether a record exists, run a query for the key and then check the returned Recordset's EOF property. When the key comes from the request, pass it as an ADO parameter rather than concatenating it into SQL.
SELECT emp_no, name FROM emp_m WHERE emp_no = ?
Dim conn, cmd, rs, empNo
empNo = Trim(Request.QueryString("emp_no"))
Set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = aConnectionString
conn.Open
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = "SELECT emp_no, name FROM emp_m WHERE emp_no = ?"
cmd.CommandType = adCmdText
cmd.Parameters.Append cmd.CreateParameter("pEmpNo", adInteger, adParamInput, , CInt(empNo))
Set rs = cmd.Execute
If rs.EOF Then
Response.Write "No matching record"
Else
Response.Write "Name: " & Server.HTMLEncode(CStr(rs("name")))
End If
rs.Close
Set rs = Nothing
Set cmd = Nothing
conn.Close
Set conn = Nothing
This example assumes adovbs.inc is included so constants such as adInteger, adParamInput and adCmdText are available. Validate that the request value is numeric before calling CInt().
When looking up an integer key, verify that the submitted value is numeric and in the expected range before calling CLng(). ADO parameters protect the SQL structure but do not replace input validation.
A successful query can return an empty Recordset. Check rs.EOF before reading rs("name"); distinguish “no match” from an actual database connection error.
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.