tags:

views:

50

answers:

2

In Access 2007, I'm trying to use the NTlogin to retrieve a value from a table via a SQL query (see code below). WHen the form loads, I get an error message saying "Compile Error: Expected Function or Variable". Can someone tell me how to fix this error.

Private Sub Form_Load()

    Dim UserName As String
    Dim strSQL As String
    Dim strDept As String

    UserName = Environ("USERNAME")

    strSQL = "SELECT DEPT FROM IDs WHERE NTLOGIN =" & UserName

    strDept = DoCmd.RunSQL(strSQL)

    cmdSave.Enabled = False
    cmdEdit.Enabled = True
    cmdPrevious.Enabled = True
    cmdNext.Enabled = True

End Sub
A: 

I haven't touched Access for some time, so I don't recall: is Environ("USERNAME") returning the USERNAME environment variable?

If so, then you have a security hole in your code. Specifically, you're open to a SQL Injection attack.

Imagine that before they run Access, a user sets the USERNAME environment variable to something like

''; DROP TABLE IDS;

In that case, you'll be executing the statement:

SELECT DEPT FROM IDs WHERE NTLOGIN =''; DROP TABLE IDS;

You may not want that to happen...

John Saunders
My ultimate goal is to use the user's department to determine which forms are enabled for that user. The table the username values reside in also contains the department field. After the user enters/selects their username, what would be the best way for me to return the department value and use it to enable/disable various forms?
hastur1
I can see your point, but Access will only execute one sql statement.
Remou
You could use some sort of string function to check the value and make sure it's a legitimate login before the SQL is run, correct?
hastur1
Since Jet/ACE cannot execute multiple SQL commands, there is no danger in the specific exploit, but certainly since environment variables can be changed by the user, there's no guarantee that the value stored there is the actual logged-on user's name. For more on the SQL injection vulnerabilities of Access see http://stackoverflow.com/questions/512174/non-web-sql-injection/522382#522382
David-W-Fenton
+1  A: 

You cannot use RunSQL with a select statement. It is only for action queries.

If you want a recordset, you can say, amongst other things:

strSQL = "SELECT DEPT FROM IDs WHERE NTLOGIN ='" & UserName & "'"
Set rs=CurrentDB.OpenRecordset(strSQL)

Where rs is DAO.Recordset

Remou
Awesome! That took care of the error message. Now how do I take the result of the query and assign it to a variable or otherwise use it?
hastur1
`yourVariable = rs!DEPT`
HansUp
And don't forget those quotes mentioned in other posts.
Remou
Awesome. No more errors and the department value is now safely stored in a variable. I'm assuming now all I have to do is use an IF statement to enable/disable forms based on the user's department. I guess if you don't use this stuff you really do lose it. Thanks for all your help.
hastur1