ASP Compare server variable with DB recordset - asp-classic

I'm new to this old scripting language but it's all we have right now. I'm trying to get this code work.
I would like to compare USERID servervariable with the same USERID from a recordset, then if true it will redirect the name of that USERID.
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Driver={Microsoft Access Driver (*.mdb)}; DBQ=I:\storyData.mdb"
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT USERIDFROM preprod", conn
strName = "John"
strNo = "This is not you"
If Request.ServerVariables("HTTP_USERID") = (rs.Fields.Item("USERID").Value) Then
Response.Redirect("story.html?" & "name=" & strName)
Else
Response.Redirect("story.html?" & "name=" & strNo)
End If
%>
I hope this makes any sense. It seems simple but can't get it to work.
thanks

what "doesn't" work?
looking at your code, it seems you're only checking the the first record of your query. I think you want to do something like this:
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Driver={Microsoft Access Driver (*.mdb)}; DBQ=I:\storyData.mdb"
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT count( USERID ) FROM preprod where userID = " & Request.ServerVariables("HTTP_USERID"), conn
strName = "John"
strNo = "This is not you"
if CInt( rs( 0 ) ) > 0 then
Response.Redirect("story.html?" & "name=" & strName)
Else
Response.Redirect("story.html?" & "name=" & strNo)
End If
%>
this code does a count of userIDs in your table and if there are more than 1, it'll do the redirect properly. A lot more efficient this way.

Related

Classic ASP and MS Access Batch Update

I am using the following code to update an Access Database with Classic Asp:
<%# Language=VBScript %>
<% Option Explicit %>
<%
Response.Buffer = True
'First, we need to get the total number of items that could be updated
Dim iCount
iCount = Request("Count")
'We need to obtain each cost and ID
Dim strstudent, strcourse, strgrade, strcomments
'We will also need to build a SQL statement
Dim strSQL
Dim conn
set conn=server.CreateObject("ADODB.connection")
conn.ConnectionString="provider=Microsoft.jet.OLEDB.4.0;data source=C:\db\agsystem.mdb"
conn.Open
'Now, we want to loop through each form element
Dim iLoop
For iLoop = 0 to iCount
'student data
strstudent = Request(iLoop & ".Student")
'course data
strcourse = Request(iLoop & ".course")
'grade
if isNull(Request(iLoop & ".grade")) or Request(iLoop & ".grade")="" then
strgrade="null"
else
strgrade= Request(iLoop & ".grade")
end if
if isNull(Request(iLoop & ".comments")) or Request(iLoop & ".comments")="" then
strcomments=null
else
strcomments=Request(iLoop & ".comments")
end if
strSQL = "UPDATE testing SET semester2 = " & strgrade & ", commentss=" & "'" & strcomments & "'" & " WHERE newstudentid = " &"'"& strstudent&"'" & " and Courseid = " & "'"& strcourse & "'"
conn.Execute strSQL
Next
conn.Close
Set conn = Nothing
Response.Redirect "protected.asp"
%>
The problem is that when tested in the server it updates without any issues. But when access from a wireless network it won't update.
The target table to update has about 27,000 records
I need to know what I'm doing wrong or if there is another approach.
I found the error after carefully analyzing the situation.
Records in primary key that have spaces for example '2 OR 13' will not update. But records without spaces in primary key like '2CEN13' updates perfectly. I did not had time to solve it in my asp code, so i edited all records with spaces and that solve the problem.

Syntax error (missing operator) in query expression

I know it is a common error, but I still can't solve it myself.
What I am trying to do is I have a SELECT item called status that allow the user to choose their employment status, I want to simply get the result and update the user_table(access file) status cell.
Any reply will be greatly appreciated!
The Code is below:
<!--#include file="../conn/conn.asp"-->
<%
id=request.QueryString("id")
status=request.Form("status")
sql="select * from user_table where id="&id
set rs=conn.execute(sql)
sql="update user_table set Status='"+status+"' where id="&id
'response.Write sql
conn.execute(sql)
conn.close
response.Write "<script>alert('Change Sucessful!');</script>"
set conn=nothing
response.end()
%>
I think you may be having a problem with conn.execute(sql) as well as response.end()
To fix it, you need to do either:
conn.execute sql
or
Call conn.execute(sql)
But, yeah, you should follow other comments posted as your technique has security issues. You should consider changing it to use parameters:
<!--#include file="../conn/conn.asp"-->
<%
id = request.QueryString("id")
status = request.Form("status")
sql = "select * from user_table where id = #id"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = sql
Set cmd.ActiveConnection = conn
cmd.Prepared = True
cmd.Parameters.Refresh
cmd.Parameters("#id") = id
Set rs = cmd.Execute
Set rs = nothing
Set cmd = nothing
sql = "update user_table set status = #status where id = #id"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = sql
Set cmd.ActiveConnection = conn
cmd.Prepared = True
cmd.Parameters.Refresh
cmd.Parameters("#status") = status
cmd.Parameters("#id") = id
Set rs = cmd.Execute
Set rs = nothing
Set cmd = nothing
response.Write "<script>alert('Change Sucessful!');</script>"
Set conn = nothing
response.end
%>
I'm guessing conn.asp leaves conn open? otherwise you need to open it. Also, what shows when you uncomment the response.write sql line?
And, you are definitely opening yourself to hackers. You need to 'clean' anything that comes from a request.form or request.querystring (with at the very least, a replace(..., "'", "''"), or much better, use stored procedures instead of straight sql

get value from asp result set

In the following asp page I am trying to get the fullName attribute from the first row of the result set. (there should only be one row) What is the right way to do this?
<%
set Y = server.CreateObject("ADODB.Connection")
X = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ= " & Server.MapPath(".\account.mdb")
Y.open X
user=request.Form("username")
passwd=request.Form("pwd")
set userexsist=Y.Execute("select * from logintable where username='" & user & "'")
set useraccount=Y.Execute("select * from logintable where username='"& user & "' and passwd='" & passwd & "'")
if userexsist.eof then
Response.Redirect("41697hw1noaccount.htm")
else
if useraccount.eof then
Response.Redirect("41697hw1wrongpasswd.htm")
else
Response.Write("<h1>Welcome, " & useraccount[0].fullName & "</h1>")
End if
end if
%>
The error is on `useraccount[0].fullName.
Whats the right way to get this information?
Thanks for your help!
Here's your code with as much wrong stuff as I could spot fixed:
I did test it, but not with an Access database.
It should work, but I only have a working knowledge of Classic ASP.
<%
Set Conn = Server.CreateObject("ADODB.Connection")
Set RS = Server.CreateObject("ADODB.Recordset")
Set RS2 = Server.CreateObject("ADODB.Recordset")
Conn.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ= " & Server.MapPath(".\account.mdb")
user = Request.Form("username")
passwd = Request.Form("pwd")
RS.Open "select * from logintable where username='" & user & "'", Conn
if RS.eof then
Response.Redirect("41697hw1noaccount.htm")
else
RS2.Open "select * from logintable where username='" & user & "' and passwd='" & passwd & "'", Conn
if RS2.eof then
Response.Redirect("41697hw1wrongpasswd.htm")
else
Response.Write("<h1>Welcome, " & RS2("fullName") & "</h1>")
end if
end if
%>

An example of advanced database search

im looking for an example script. I saw one yesterday but for the life of me I can't find it again today.
The task I have is to allow the user to search 1 database table via input controls on an aspx page where they can select and , or , equals to combine fields, generating the sql on the fly with concat/stringbuilder or similar. (it runs behind the corp firewall)
Please can someone point me in the right direction of an example or tutorial
I've been working on the page, but have run into problems. Here is the Page_load;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = ("Select * From Table Where ")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty Then
sql += "Surname LIKE '%" & name & "%' "
End If
If EmailSearch.Text IsNot String.Empty Then
sql += andor1v & " Email LIKE '%" & email & "%' "
End If
If CitySearchBox.Text IsNot String.Empty Then
sql += andor2v & " City LIKE '%" & city & "%' "
End If
If QualificationsObtained.Text IsNot String.Empty Then
sql += andor3v & " (institutionquals1 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals2 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals3 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals4 LIKE '%" & qualifications & "%') "
End If
Dim selectedrow As String = CompetenciesDD.SelectedValue.ToString
Dim selectedquals As String = NQFlevel.SelectedValue.ToString
If CompetenciesDD.SelectedValue.ToString IsNot "0" And selectedquals = 0 Then
sql += (selectedrow & " = 1 ")
ElseIf selectedrow = "assessortrue" And selectedquals IsNot "0" Then
sql += andor4v & (" assessortrue=1 and assessorlvl=" & selectedquals)
ElseIf selectedrow = "coordinatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("coordinatortrue=1 and coordinatorlvl=" & selectedquals)
ElseIf selectedrow = "facilitatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("facilitatortrue=1 and facilitatorlvl=" & selectedquals)
ElseIf selectedrow = "moderatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("moderatortrue=1 and moderatorlvl=" & selectedquals)
ElseIf selectedrow = "productdevelopertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("productdevelopertrue=1 and productdeveloperlvl=" & selectedquals)
ElseIf selectedrow = "projectmanagertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("projectmanagertrue=1 and projectmanagerlvl=" & selectedquals)
End If
Response.Write(sql)
End Sub
After an hours tinkering the code is now looking as it does above ^
Now the problem im faced with is if a user does not enter a value for surname (the first field) but does enter a value for email (or any subsequent fields), the sql produced has an extra and like this;
Select * From Table Where And Email LIKE '%test%'
I'm also looking for a way to take the OR option into account. Do you think this should be done as Martin says where the whole query is either an and or an or and not a mix of the 2? Then I should be able to take out all the and/or drop downs?
Thanks.
NB: I'm not really looking for comments on how I should parameterise or about sql injection.
Regarding your issue with users not selecting an option you could just remove the "please select" and have it default to "and"
Also what is the desired behaviour if they select a mix of ANDs and ORs?
By default the ANDs will be evaluated first in the absence of any brackets
http://msdn.microsoft.com/en-us/library/ms186992.aspx
So if they enter
name="Fred" or email="blah" and
city="london" and province="xyz" or
qualifications="Degree"
I'm not really sure what the desired semantics would be?
Is it
(name="Fred" or email="blah") and
city="london" and (province="xyz" or
qualifications="Degree")
or
(name="Fred" or (email="blah" and
city="london") and province="xyz") or
qualifications="Degree"
Or something different? Maybe you should restrict them to AND or OR for the whole query or allow them to disambiguate either by typing in advanced search syntax with brackets or by providing a query builder UI.
To avoid sql injection and allow a dynamic search I would probably write a stored procedure something like this. If nothing is selected send DBNull.Value in the ado.net parameters collection as the parameter value. With this approach you can check any columns you want and if they are not selected by the user they will be ignored.
EDIT: I just saw that you are not allowed to use stored procedures. I changed my answer below to show a parameterized sql statement
SELECT * FROM TABLE
WHERE ([name] = #name OR #name IS NULL)
AND (email = #email OR #email IS NULL)
AND (city = #city OR #city IS NULL)
AND (province = #province OR #province IS NULL)
AND (qualifications = #qualifications OR #qualifications IS NULL)
AND (competencies = #competencies OR #competencies IS NULL)
AND (expertise = #expertise OR #expertise IS NULL)
Concat strings to build a query is never a good idea. You should use a stored procedure or parametrized queries
I have done this "dynamic" type query interface on classic asp.
The advice that I give to you is that you are trying to do the whole query in one page load so...
Look to "building" the query via a "wizard" type interface - either ajax for the newness or simple multiple pages for each part of the query building.
This is essence gives you "persitance" via what ever means you have (session, dbstore, cookie etc) for each part of the query and you have can sanity check each part of the query as you build.
Dim sql As String = ("Select * From Table Where **1=1**")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty And andor1v IsNot "0" Then
sql += "**and** Surname LIKE '%" & name & "%' "
ElseIf NameSearch.Text IsNot String.Empty And andor1v Is "0" Then
sql += "**or** Surname LIKE '%" & name & "%' "
End If
....additional logic here.....
Response.Write(sql)
End Sub
note the ** parts. 1=1 evaluates to true on most DBMS. This allows you to just start concatenating your or / ands on to it without worrying about ()'s

Querying Active Directory using VBScript

I want to query Active Directory using VBScript (classic ASP).
How can I accomplish that?
To look at all the members of an OU, try this...
Set objOU = GetObject("LDAP://OU=YourOU,DC=YourDomain,DC=com")
For each objMember in ObjOU ' get all the members'
' do something'
Next
To do a custom search for DNs try this...
set conn = createobject("ADODB.Connection")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
strQueryDL = "<LDAP://" & strDefaultNamingContext & ">;(&(objectCategory=person)(objectClass=user));distinguishedName,adspath;subtree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' we want to search everything
objCmd.Properties("Page Size") = 500 ' and we want our records in lots of 500
objCmd.CommandText = strQueryDL
Set objRs = objCmd.Execute
While Not objRS.eof
' do something with objRS.Fields("distinguishedName")'
objRS.MoveNext
Wend
I had to query WinAD by oldskool username, this .vbs script prints user accounts.
find by sAMAccountname, use * wildcard
print few attributes from each user object
use AccountType filter its most optimized way of iterating AD user objects
Test script first gets an user object by fully qualified string, its just an example. Second part does actual query by smith* filter.
WinADSearch.vbs
' c:> cscript -nologo script.vbs
' c:> wscript script.vbs
' http://msdn.microsoft.com/en-us/library/d6dw7aeh%28v=vs.85%29.aspx
' WindowsAD queries
' http://www.kouti.com/tables/userattributes.htm
Option Explicit
'On Error Resume Next
Dim StdOut: Set StdOut = WScript.StdOut
Dim objUser
Set objUser = GetObject("LDAP://CN=Firstname Lastname,OU=Internal Users,OU=MyCompany,OU=Boston,OU=Root,DC=REGION1,DC=COM")
println(objUser.givenName & " " & objUser.middleName & " " & objUser.lastName)
println("name=" & objUser.name)
println("displayName=" & objUser.displayName)
println("userPrincipalName=" & objUser.userPrincipalName)
println("sAMAccountName=" & objUser.sAMAccountName)
println("distinguishedName=" & objUser.distinguishedName)
println("")
Dim conn, strQueryDL, strAttrs, objCmd, objRs, idx
set conn = createobject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "ADs Provider"
strAttrs = "sAMAccountName,displayName,distinguishedName" ' get attributes
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person) );" & strAttrs & ";SubTree"
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person)(objectClass=user) );" & strAttrs & ";SubTree"
'strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (objectCategory=person)(objectClass=user)(sAMAccountName=smith*) );" & strAttrs & ";SubTree"
strQueryDL = "<LDAP://dc=REGION1,dc=COM>;(& (samAccountType=805306368)(sAMAccountName=smith*) );" & strAttrs & ";SubTree"
set objCmd = createobject("ADODB.Command")
objCmd.ActiveConnection = Conn
objCmd.Properties("SearchScope") = 2 ' search everything
objCmd.Properties("Page Size") = 100 ' bulk operation
objCmd.CommandText = strQueryDL
println(objCmd.CommandText)
Set objRs = objCmd.Execute
idx=0
do while Not objRS.eof
idx=idx+1
println( objRs.Fields("sAMAccountName") & " / " & objRs.Fields("displayName") & " / " & objRs.Fields("distinguishedName") )
if (idx>5) then exit do
objRS.MoveNext
loop
objRs.Close
Conn.close
set objRs = Nothing
set conn = Nothing
println("end")
'********************************************************************
Sub println(ByVal str)
If (StdOut Is Nothing) Then Exit Sub
StdOut.WriteLine str
End Sub
You want to use Active Directory Service Interfaces (ADSI)
The ADSI Scripting Primer is a good place to start learning and find examples.
(btw, these links refer to Windows 2000, but are valid for subsequent versions of Windows as well).

Resources