如何比较数组中的数字与结果集?

时间:2017-05-03 09:20:37

标签: mysql asp-classic

以下代码比较项目用户先前已从数据库中选择了项目ID,并“检查”了所选项目。所以我有一个所有项目的复选框列表,其中只有他们之前选择的项目被“检查”。这是针对更新订单页面

Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open Application("strConn")

strSQL = "SELECT * FROM Items"

'current items selected 
'e.g. 31, 32, 33                    
strItemSelected = curr_Item_IDs & ","                                   

set rs = Conn.Execute(strSQL)

If Not rs.EOF Then

Do while not rs.EOF

response.write "<input type = 'checkbox' "

If InStr(strItemSelected, CStr(rs("ID")) & ",") > 0 Then

response.write("checked = 'checked' ")

END if                  

response.write(" name='item' value=""" & rs("ID") & """> " & 
rs("item_name") & vbcrlf)
response.write("/     ID: " & rs("ID") & "<br />")                                          

rs.movenext

Loop

end if

set rs=nothing

这段代码的作用是ID为31,它选择“31”但也选择“1”。我确实认为它的InStr引起了这个问题,但不确定如何纠正这个问题。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

一种方法是调整查询以包含计算列:

'change your query... '
strSQL = "SELECT I.*, case when I.ID in (" & strItemSelected & ") then 'Y' else 'N' end as selected FROM Items I"

然后在你的循环中,用这个替换你的IF:

If rs("selected") = "Y" Then
    response.write("checked = 'checked' ")
END if  

如果您必须使用代码中的逻辑并且无法更改查询,则可以使用数组而不是尝试使INSTR工作...

Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open Application("strConn")    
strSQL = "SELECT * FROM Items"

'current items selected 
'e.g. 31, 32, 33                    
'-----Create an array here instead of a string------
arrItemSelected = SPLIT(curr_Item_IDs,",")

set rs = Conn.Execute(strSQL)

If Not rs.EOF Then        
    Do while not rs.EOF        
        response.write "<input type = 'checkbox' "
        '----Loop through the array-----
        For i=0 To UBound(arrItemSelected) Step 1
            If arrItemSelected(i) = CStr(rs("ID")) Then
               response.write("checked = 'checked' ")
            END if  
        Next

        response.write(" name='item' value=""" & rs("ID") & """> " & 
        rs("item_name") & vbcrlf)
        response.write("/     ID: " & rs("ID") & "<br />")                                          

        rs.movenext

    Loop
End If