Parameterised query asp classic missing operand error - asp-classic

I am trying to get a paramterised query to work in asp classic. Any help appreciated
Here is the error
Microsoft OLE DB Provider for Visual FoxPro error '80040e14'
Missing operand.
/portal/jobportal/getaddress1.asp, line 141
function paramQuery()
code = ucase(request.querystring("code"))
stype = request.querystring("type")
cAddressType = request.querystring("caddresstype")
Set rs = Server.CreateObject("ADODB.recordset")
Set cmd = server.CreateObject("ADODB.Command")
If IsObject(Session("portal_conn")) Then
Set conn = Session("portal_conn")
Else
Set conn = Server.CreateObject("ADODB.Connection")
cConnString = "Provider=vfpoledb;Data Source="+session("portaldata")+"portal.dbc"
conn.open cConnString,"",""
Set Session("portal_conn") = conn
end if
cmd.ActiveConnection = conn
cmd.Prepared = true
cmd.CommandType = 1
cmd.CommandText = "SELECT * from uaddress where userid = "+cstr(session("userid"))+" and upper(name) like ? + % "+" and type = '"+ trim(cAddresstype)+"' order by add1"
set param1 = cmd.CreateParameter("#name",200,2,40)
cmd.Parameters.append param1
cmd.Parameters("#name") = code
cmd.Execute() <-- missing operand error
rs.Open cmd
end function

When using parameter for SQL like clause you need to pass the % as part of the parameter value.
Also to protect against SQL Injection attacks you really better use parameters for the other values as well:
cmd.CommandText = "SELECT * FROM uaddress WHERE userid=? AND UPPER(name) LIKE ? AND type=? ORDER BY add1"
set param1 = cmd.CreateParameter("#id", 200, 2, 40)
cmd.Parameters.append param1
cmd.Parameters("#id") = cstr(session("userid"))
set param2 = cmd.CreateParameter("#name", 200, 2, 40)
cmd.Parameters.append param2
cmd.Parameters("#name") = "%" & code & "%"
set param3 = cmd.CreateParameter("#type", 200, 2, 40)
cmd.Parameters.append param3
cmd.Parameters("#type") = trim(cAddresstype)
cmd.Execute()

You need quotes around the % character:
... +" and upper(name) like ? + '%' "+ ...

It seems like VFP does not support named parameters , just add your params in the order that apears in the query by using (?) instead of the named param and it will work.
instead of :
cmd.Parameters("#name") = code
Use :
cmd.Parameters("?") = code

Related

How to prevent SQL injection in classic ASP [duplicate]

My db access code is like following:
set recordset = Server.CReateObject("ADODB.Recordset")
set cmd1 = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = Conn //connection object already created
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd1.CommandType = adCmdText
set prm = cmd1.CreateParameter("#prm", 200, 1,200 , "development")
cmd1.Parameters.Append prm
set recordset = cmd1.Execute
But there is no db hit going. Please help with this. I am using sql server 2005.
Thanks.
In my code, this is how I get a recordset from a command:
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
cmd.ActiveConnection = Conn //connection object already created
cmd.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
set prm = cmd.CreateParameter("#prm", 200, 1, 200, "development")
cmd.Parameters.Append prm
' Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
Hope it helps
I like using Parameters.Refresh, i.e.
set recordset = Server.CReateObject("ADODB.Recordset")
set cmd1 = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = Conn ' connection object already created
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd1.CommandType = adCmdText
cmd1.Prepared = True ' only needed if u plan to reuse this command often
cmd1.Parameters.Refresh
cmd1.Parameters(0).Value = "development"
set recordset = cmd1.Execute
Looks like you aren't referencing your named parameter correctly in your query.
Try replacing:
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
with:
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = #prm"
and see if that helps.
If you have a complex criteria using parameters here is an example I had to create based on my requirements
declare #loc smallint = ? , #dt1 date = ? SET #loc = ISNULL(#loc, 999)
SELECT m.* , c.*
FROM Costs c INNER JOIN MbrData m ON c.SN = m.SN and c.startDT = m.startDT
WHERE (m.LocationID = #loc OR #loc = 999) AND (MonthYear = #dt1 OR #dt1 IS NULL)
ORDER BY m.LocationID
then in your asp
cmd.CommandText = strSQL ' the string above
cmd.CommandType = 1 ' adCmdText
cmd.Parameters.Append cmd.CreateParameter("#loc",2,1) 'adSmallInt=2, adParamInput=1
cmd.Parameters("#loc") = rptlocation ' scrubbed location ID
cmd.Parameters.Append cmd.CreateParameter("#dt1",7,1) 'adDate=7, adParamInput=1
cmd.Parameters("#dt1") = scrubbed formatted date
set rst = cmd.Execute
Try leaving off the parameter name:
set prm = cmd1.CreateParameter(, 200, 1,200 , "development")

Response.Redirect error

I have form page that collects data. The user clicks SUBMIT, which goes to a "post page. At the end of this page is the redirect code I am using.
response.redirect( "test.asp?ChecklistID=" + ChecklistID )
For some reason, the result is this.
/test.asp?ChecklistID=4784,%204784
Why is this returning in TWO ID's? I only have ONE record in the 'results' table. And it is '4784'.
Adding the code
<%
'Option Explicit
Dim SQLStmt, sql, RS, ChecklistID, Location, ChecklistDate, Driveup,
ConnectString, conn, objconn
Dim weeds, parking_lot, sidewalk, windows, exterior_trash, door_clean
Dim mats_clean, Notes_page1
Location = Request("Location")
ChecklistDate = Request("ChecklistDate")
Driveup = Request("Driveup")
ChecklistID = Request("ChecklistID")
weeds = Request("weeds")
parking_lot = Request("parking_lot")
sidewalk = Request("sidewalk")
windows = Request("windows")
exterior_trash = Request("exterior_trash")
door_clean = Request("door_clean")
mats_clean = Request("mats_clean")
Notes_page1 = Request("Notes_page1")
ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
Server.MapPath("../xyz/mydatabase.mdb")
Set conn = Server.CreateObject("ADODB.Connection")
conn.open ConnectString
SQLStmt = "SELECT * FROM Results WHERE ChecklistID =" & ChecklistID & " ; "
Set RS = Server.CreateObject("ADODB.Recordset")
RS.open "Results", conn, 3, 3
RS.Update
RS("ChecklistDate") = ChecklistDate
RS("Driveup") = Driveup
RS("weeds") = weeds
RS("parking_lot") = parking_lot
RS("sidewalk") = sidewalk
RS("windows") = windows
RS("exterior_trash") = exterior_trash
RS("door_clean") = door_clean
RS("mats_clean") = mats_clean
RS("Notes_page1") = Notes_page1
RS.Update
RS.close
set RS = nothing
conn.close
set conn = nothing
response.redirect( "test.asp?ChecklistID=" + ChecklistID )
%>
The browser might be retaining some history with response.redirect. Try using Server.Transfer. Or, if it's the same page, you might not have to re-add the query string.
Solved
I had the same hidden field in there twice causing the issue.

I need help parameterizing some VBScript code in an .asp file

Here is a snippet of what I'm working on. Please let me know if I need to post more:
<% # LANGUAGE = VBScript ENABLESESSIONSTATE = False %>
<!--#include file="Connections/ConnectionString.asp" -->
<!--#include file="SqlCheckInclude.asp" -->
<%
Dim LoginTest
LoginTest = ""
If Request.QueryString("Action") = "Login" Then
Dim IsUserNameLocked
Set IsUserNameLocked = Server.CreateObject("ADODB.Recordset")
IsUserNameLocked.ActiveConnection = ConnectionString
sProUserName = Request.Form("ProUserName")
sanitizedProUserName = "'" & Replace(sProUserName, "'", "''") & "'"
Response.Write(sanitizedProUserName)
Response.End()
IsUserNameLocked.Source = "SELECT IL_Date, IL_Timer, IL_NumOfTimes, ProUserName FROM PROFILE WHERE ProUserName =" & sanitizedProUserName
IsUserNameLocked.CursorType = 2
IsUserNameLocked.CursorLocation = 3
IsUserNameLocked.LockType = 3
IsUserNameLocked.Open
if not IsUserNameLocked.eof then
intNumOfIncorrectLogin = IsUserNameLocked("IL_NumOfTimes")
InCorrectLoginDate = IsUserNameLocked("IL_Date")
InCorrectLoginTime = IsUserNameLocked("IL_Timer")
end if
IsUserNameLocked.close
set IsUserNameLocked = nothing
end if
%>
I attempted to convert it to:
If Request.QueryString("Action") = "Login" Then
Dim IsUserNameLocked
Set IsUserNameLocked = Server.CreateObject("ADODB.Recordset")
IsUserNameLocked.ActiveConnection = ConnectionString
strSql = "SELECT IL_Date, IL_Timer, IL_NumOfTimes, ProUserName FROM PROFILE WHERE ProUserName = ?"
strSearch = Request.Form("ProUserName")
set objCommand = Server.CreateObject("ADODB.Command")
objCommand.ActiveConnection = ConnectionString
objCommand.CommandText = strSql
objCommand.Parameters(0).value = strSearch
IsUserNameLocked.results = objCommand.Execute()
IsUserNameLocked.CursorType = 2
IsUserNameLocked.CursorLocation = 3
IsUserNameLocked.LockType = 3
IsUserNameLocked.Open
end if
But this did not work. I have been searching online for the past few hours attempting to find a method that properly works, but I'm getting no functioning results. If someone could please help with an implementation that properly parameterizes and protects against SQL injection, I would be extremely grateful.
According to the docs, you need to .Append a parameter to a Command's parameter collection. Evidence:
>> Set oCmd = CreateObject("ADODB.Command")
>> WScript.Echo "# parameters", oCmd.Parameters.Count
>> oCmd.Parameters(0).Value = "no such thing"
>>
# parameters 0
Error Number: 3265
Error Description: Item cannot be found in the collection corresponding to the requested name or ordinal.
Do you use a global On Error Resume Next?

query string in classic asp code to catch integer values

I have written below code piece that is supposed to search from DB based on two Parameters
Integer value(ID of a SHIP)
String value(SHIP name).
But with the following code I am able to get data from the DB using the SHIP name i.e using the 2nd case. But unable to search the data using the ID of the SHIP.
Following is the code snippet. Any help on these is highly appreciated.
nIMO = sql_ship_friendly(request.querystring("nIMO"))
if IsNumeric(nIMO) = false then
nIMO = ""
else
nIMO = cInt(nIMO)
end if
sVessel = sql_ship_friendly(UCase(request.querystring("sVessel")),10)
if not nIMO = "" then
'search based on vessel id
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP, COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR, 0) AS YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE ACTIVE_IND='Y' AND IMO_NBR = 7723948"
Set db1 = Server.CreateObject("ADODB.Connection")
db1.Open GV_VIEW_DB_String
Set rs = db1.Execute(sql)
Set dbl = nothing "
elseif not sVessel = "" then
'search based on vessel number
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP, COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR , 0) AS YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE VESSEL_NM LIKE '"&SVESSEL&"%' AND ACTIVE_IND='Y'"
' response.write sql Set db1 =
Server.CreateObject("ADODB.Connection") db1.Open GV_VIEW_DB_String
Set rs = db1.Execute(sql) Set dbl = nothing
if your first case you have placed following
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP,
COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR, 0) AS
YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE ACTIVE_IND='Y' AND IMO_NBR =
7723948"
but I can see you are using the nIMO perameter in query. Put it and you should get result..
You can use it like AND IMO_NBR = nIMO or likewise.
The problem is there is no where on your SQL statement that use nIMO variable as your search criteria. Forget about using IsNumeric(nIMO) = false... Use isNull function instead. Try this.
if not isnull( request.querystring("nIMO")) then
nIMO = cInt(nIMO)
sql = "SELECT IMO_NBR, VESSEL_NM, COALESCE(SHIP_TYP,'0') AS SHIP_TYP," &_
"COALESCE(DWT_WT, 0) AS DWT_WT, COALESCE(YEAR_BUILT_NBR, 0) AS " &_
"YEAR_BUILT_NBR FROM RSP_VESSEL_VW WHERE ACTIVE_IND='Y' AND " &_
"IMO_NBR =" & nIMO
...
...
...
end if

Updateing NText causing long delay/timeouts

I'm trying to update an NText field in SQL 2000 using Classic ASP. Here is the code I'm using to do it. Any one have any pointers on how to maybe speed it up? Or am I stuck with it.
set Cnn = server.CreateObject("ADODB.connection")
Cnn.ConnectionString = Application("Cnn_ConnectionString")
Cnn.open
set rs = server.CreateObject("ADODB.Recordset")
rs.CursorType = adoOpenDynamic
rs.LockType = adLockOptimistic
conChunkSize = 100
rs.Open "MyTable",Cnn, , , adCmdTable
rs.Find "MyDataId=" & request("DataId"),,adSearchForward,1
lngOffset = 0
lngLogoSize = len(request("txtMyEntry"))*2
Do while lngOffset < lngLogoSize
varChunk = LeftB(RightB(request("txtMyEntry"), lngLogoSize - _
lngOffset), conChunkSize)
rs("MyDataField").AppendChunk varChunk
lngOffset = lngOffset + conChunkSize
Loop
rs.Update
rs.Close
Oh and this code is almost verbatim from the MSDN site.
First I would eliminate the chunking which is so 90's.
Then there is:-
rs.Open "MyTable",Cnn, , , adCmdTable
rs.Find "MyDataId=" & request("DataId"),,adSearchForward,1
Yikes! You'd like to think that ADO intelligently asked SQL server to find that record based on the indexed MyDataId field but bet it doesn't. Its most likely pulling the entire contents of the table across until the record is arrived at.
This really should be done with an UPDATE T-SQL statement and an ADODB.Command object.
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = cnn
cmd.CommandType = 1 '' // adCmdText
cmd.CommandText = "UPDATE MyTable SET MyDataField = ? WHERE MyDataId = ?"
cmd.Parameters.Append cmd.CreateParameter("dataField", 203, 1, Len(txtMyEntry), txtMyEntry) '' // 203 = asLongVarWChar, 1 = adParamInput
cmd.Parameters.Append cmd.CreateParameter("id", 3, 1, , CInt(DataID)) '' // 3 = adInteger
cmd.Execute

Resources