I've been working on this script for the last week or so and i'm having major problems trying to understand why it's not working right.
I've got some checkboxes link to email address and all i need is for the corresponding username to go with that email. This script is for users that have registered for different newsletters.
Here is my coding
Set conn = Server.CreateObject("ADODB.Connection")
conn.open connStr
emails = Request("emaillist")
emails = Replace( emails, "'", "''" )
emails = Replace( emails, ", ", "','" )
strSQL = "SELECT name, email FROM emails WHERE email IN ('" & emails & "')"
Set rs = conn.Execute(strSQL)
namesAndEmails = rs.GetRows()
rs.close
for lnRowCounter = 0 To Ubound(namesAndEmails,2)
For lnColumnCounter = 0 To Ubound(namesAndEmails,1)
Response.Write namesAndEmails(lnColumnCounter, lnRowCounter)
Response.write "</P>"
Next
Next
This is part of the whole script, i've changed it around a bit and included the for...next for debugging.
Now for the problem, as shown in the SELECT statement 'name, email', the result completely ignores the email and give me the names only.
I've tried the SQL statement direct and it works perfect showing both name and email together but not in my ASP page. I even tried putting a * in it's place.
strSQL = "SELECT * FROM emails WHERE email IN ('" & emails & "')"
Will return the users id, name, and a few other item's from the DB but not the name and emails together, why?????
It's asp with a SQL Server database
Regards
Rick
Test Results
The values from strSQL when it's set as this:
SELECT name, email
FROM emails
WHERE email IN ('test#test.com','test1#test1.com')
This in SQL will give me the following answer
name | email
jo | test#test.com
fred | test1#test1.com
In asp the answer will be
test#test.com
test1#test1.com
I can't figure out why in SQL it will show the name and email but in ASP it will only show the email and NOT the name.
I've even tried
strSQL = "SELECT * FROM emails WHERE email IN ('test#test.com','test1#test1.com')
and this will produce in ASP all the results EXCEPT name!!!!!
I might not be understanding this completely, but if all you want to do is to output a list of names with their respective email addresses, you could try simplifying to this:
name = rs("name")
email = rs("email")
do while rs.eof <> true
response.write(name & " " & email & "<br />")
rs.movenext
loop
…at least for testing purposes. Alternatively, you could concatenate the name and email in the SQL statement into one column:
SELECT name + '|' + email as nameemail FROM emails WHERE email IN ('" & emails & "')
...will give you "name|email" that you can easily string manipulate.
I'm not 100% sure, but I guess you must swap the rank parameter of the ubound()
for lnRowCounter = 0 To Ubound(namesAndEmails,1)
For lnColumnCounter = 0 To Ubound(namesAndEmails,2)
Try
For i = LBound(namesAndEmails, 2) To UBound(namesAndEmails , 2)
Name = namesAndEmails(0, i)
Email = namesAndEmails(1, i)
Response.Write Name & " " & Email
Next
What if you "View Source" of the output webpage. Sometimes I've had errors that I couldn't see because it came out looking like an invalid tag that the renderer would silently ignore.
Related
I've been searching hard the past few days and have come across numerous examples that outline what I'm trying to do. However, I can't seem to get this working. I have a combobox that populates data (a company name) from a table when the form initializes. I then want to take the value chosen in the combo box and run another query to cross reference an id number in that same table.
Private Sub CommandButton1_Click()
Dim myCn As MyServer
Set myCn = New MyServer
Dim rs As ADODB.recordset
Set rs = New ADODB.recordset
Dim sqlStr As String
Dim CompField As String
'CompField = ComboBox1.Value
sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = '" & ComboBox1.Text & "'"
'sqlStr = "Select DISTINCT [company] FROM client;"
' sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Value & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Text & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = 'Company XYZ';"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE company = " & CompField & ""
rs.Open sqlStr, myCn.GetConnection, adLockOptimistic, adCmdText
MsgBox sqlStr
'MsgBox ComboBox1.Value
'MsgBox rs(0)
rs.Close
myCn.Shutdown
Set rs = Nothing
Set myCn = Nothing
End Sub
Currently with the combobox value encased in single quotes i get the entire sql string returned. If I remove the single quotes I get a syntax error referencing part of the combobox value. All other efforts have resulted in run-time errors that have led me nowhere.
I know my query works because I've tested it in SQL Studio and if I hard code a text value in this code I also get the Account ID I'm looking for. Not sure what I'm missing here.
Well I figured it out. I was expecting to be able to MsgBox the variable assigned to the SQL query and see my results. But it doesn't work that way. I had to use ADO GetString method for that and assign another variable. Oh and you were right about escaping, I had to add delimters to properly handle the ComboBox value in the query which ultimately looked like this
sqlStr = "SELECT DISTINCT [acct_no] FROM client WHERE [company] = " & Chr(39) & Me.ComboBox1.Value & Chr(39)
Thanks for your help on this
I have created a macro/some VBA to UPDATE a SQL Server table which works fine.
In short the code pulls a defined amount of records from the the table to excel and then the end user updates some specific information and then clicks update. A connection is created to the table and an SQL update statement runs which updates the relevant records.
The problem is where the user has not had to update a NULL field (NULL is in the SQL Server table but shows as 'empty' in Excel), when the use clicks update the SQL statement is forcing the NULL to an 'empty' entry.
To get round this I would like my code in the For Each statement to check if the cell/record is NULL or Empty and to skip to the NEXT row so the SQL Execute command is not carried out.
Here is the VBA in question:
cnn.Open cnnstr
Dim row As Range
For Each row In [tbl_data].Rows
uSQL = "UPDATE BREACH_DATA SET [VAL_BREACH_REASON] = '" & (row.Columns(row.ListObject.ListColumns("VAL_BREACH_REASON").Index).Value) _
& "' ,[VAL_BREACH_DETAIL] = '" & (row.Columns(row.ListObject.ListColumns("VAL_BREACH_DETAIL").Index).Value) _
& "' ,[VAL_VALID] = '" & (row.Columns(row.ListObject.ListColumns("VAL_VALID").Index).Value) _
& "' ,[VAL_NOTES] = '" & (row.Columns(row.ListObject.ListColumns("VAL_NOTES").Index).Value) _
& "' WHERE [ATD_NUMBER] = '" & (row.Columns(row.ListObject.ListColumns("ATD_NUMBER").Index).Value) & "'"
'Debug.Print uSQL
cnn.Execute uSQL
Next
cnn.Close
Set cnn = Nothing
Any suggestions
Kind Regards
Dino
You are updating SQL Server data directly with strings from a cell. This is a classic example of opening a door for injection attacks - users can do all kinds of bad, bad things to your database. But given that you fix that here is a way to check that each cell is not empty or null (I assume if one of the fields are not empty or null you want to update...):
if not
(
(isempty(row.Columns(row.ListObject.ListColumns("VAL_BREACH_REASON").Index).Value)
and isnull(row.Columns(row.ListObject.ListColumns("VAL_BREACH_REASON").Index).Value)
and do same for the other cell values....
)
then update....
I am working on designing a asp form which will query an Access database (mdb). The outcome of the form is to query data results between a date range (date from and date to), and output the results on the asp page below. When I try and run the query I receive the following error:
Microsoft JET Database Engine error '80040e07'
Syntax error in date in query expression 'name = 'firstname.lastname' And date = ##'.
Note: firstname.lastname correspnds to the real person.
The code it points to two lines which appear as follows:
rstDATA.open "Select * From xxx Where name = '" & username & "' And date = #" & request.Form("ddDate") & "#",cnn, adOpenKeyset, ,adLockReadOnly %>
rstDATA.open "Select * From xxx Where name = '" & username & "' And date = #" & request.Form("ddDate") & "#",cnn, adOpenKeyset, ,adLockReadOnly %>
where xxxx corrsponds to the table.
It seems there is no value for ddDate provided. Are you sure you have a html element in your form that has a name attribute with "ddDate" as it's value?
On my form I have a button which the user can click. It will then prompt the user with 3 input boxes, where the user can enter in the information that he wants to run a query on. I want the query to run based on the values that he enters into the 3 inputboxes, but I cannot seem to figure this out. The query is based on another table in my database. Here is the code I've written. It won't compile because I have too many arguments. This is probably because I don't know how to pass variables with the DoCmd.OpenQuery command.
Private Sub VariableQuery_Click()
Dim strProdCode As String
Dim strCampCode As String
Dim strMailDate As String
strProdCode = InputBox("Enter Product Code", "Product Code")
strCampCode = InputBox("Enter Campaign Code", "Campaign Code")
strMailDate = InputBox("Enter Mail Date", "Mail Date")
DoCmd.OpenQuery "contribution", , , "[PRODUCT_CODE]=" & strProdCode & _
"[CAMPAIGN_CODE]=" & strCampCode & "[MAIL_DATE]=" & strMailDate
End Sub
Any help is appreciated. The name of the query I am trying to run is "contribution". PRODUCT_CODE, CAMPAIGN_CODE, and MAIL_DATE are the names of the fields in the database and PRODUCT_CODE and CAMPAIGN_CODE are both text fields, and MAIL_DATE is a Date/Time field.
I don't know if there is a different way to do this but how I would approach the problem is by creating the SQL string
Dim strSQL As String
strSQL = "SELECT ... INTO ... " _
& "FROM ... " _
& "WHERE [PRODUCT_CODE]='" & strProdCode &"' AND [CAMPAIGN_CODE]='" & strCampCode & "' AND [MAIL_DATE]=#" & strMailDate & "#"
DoCmd.RunSQL strSQL
Things to note
When you have WHERE kind of clauses you have to qualify the values of the fields appropriately e.g. '' around strings, ## around dates and nothing around numbers
DoCmd.RunSQL I believe only runs actions queries e.g. UPDATE, DELETE etc. Plain SELECT are not action queries.
If you want to hide the warnings that popup there are two ways to do it, one is to use CurrentDB.Execute(strSQL) instead or to use DoCmd.SetWarnings(False) and DoCmd.SetWarnings(True)
Edit (Possible helpful links)
http://allenbrowne.com/tips.html
Building SQL strings in Access/VBA
You can Google "building sql strings in ms access" or some variation of that for more sources
Started getting this error it seems since we upgraded to SQL Server 2008.
When inserting into the db and then returning the identity i get a 'Item cannot be found in the collection corresponding to the requested name or ordinal' error.
Here is the code:
SQL = "INSERT INTO PageFeatures(nPageFeatureFlagId,nPageFeatureFeatureId,nPageFeaturePageId) VALUES(" & nTemplateFlagId & "," & nFeatureId & "," & nPageId & "); SELECT SCOPE_IDENTITY() As nPageFeatureId;"
objrs.open SQL,objConn,1,1
nPageFeatureId = objrs("nPageFeatureId")
objrs.close
The insert is working as the record is in the db. It's not returning the id for some reason. It works fine and returns the id when running in SSMS. But ASP can't see the returned id so some reason.
Any help would be greatly appreciated!
You may have to try moving the recordset on? e.g.
SQL = "INSERT INTO PageFeatures(nPageFeatureFlagId,nPageFeatureFeatureId,nPageFeaturePageId) VALUES(" & nTemplateFlagId & "," & nFeatureId & "," & nPageId & "); SELECT SCOPE_IDENTITY() As nPageFeatureId;"
objrs.open SQL,objConn,1,1
objrs.NextRecordset
nPageFeatureId = objrs("nPageFeatureId")
objrs.close
Raj's comment about SQL injection is still relevant. :)
EDIT: Elaboration is that there are two recordsets in play here. The first is an empty one created by the insert statement, the second one is caused by everything after the semi-colon ;. This is the field you want. So initially, your objrs is attached to the first of its collection of recordsets (not rows in a recordset), you move to the NextRecordset - and you can then deal with that how you please.
Sorted:
SQL = "INSERT INTO PageFeatures(nPageFeatureFlagId,nPageFeatureFeatureId,nPageFeaturePageId) VALUES(" & nTemplateFlagId & "," & nFeatureId & "," & nPageId & ");"
objConn.execute(SQL)
Set oReturnValueRS = objConn.Execute("SELECT SCOPE_IDENTITY()")
nPageFeatureId = oReturnValueRS(0).Value
oReturnValueRS.close : set oReturnValueRS = nothing