Check if email exists - sql

I have a classic ASP page with some code to check if an email exists in the table as follows;
<%
'' //Check the submitted email against existing ones in the database
set CmdCheckEmail = server.CreateObject("ADODB.Command")
CmdCheckEmail.ActiveConnection = MM_dbconn_STRING
CmdCheckEmail.CommandText = "SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = '" & Request("Email") & "'"
Response.Write(CmdCheckEmail.CommandText)
CmdCheckEmail.CommandType = 1
CmdCheckEmail.CommandTimeout = 0
CmdCheckEmail.Prepared = true
CmdCheckEmail.Execute()
countEmail = CmdCheckEmail("CountEmail")
set CmdCheckEmail = nothing
conn.close
set conn = nothing
If(countEmail >= 1) Then
Message = Message & "<p>This email address has already been referred.</p>"
End If
%>
However, the page is reporting the following error;
SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = 'test#xyz.com'
ADODB.Command error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal.
/default2.asp, line 19
Line 19 is as follows;
countEmail = CmdCheckEmail("CountEmail")
The email does exist in the table and the table simply has the following columns; ReferredEmail and ReferredCode
I wondered if anyone might be able to shed any light on this error?
Thank you.

Note sure what database you are using but try changing your sql to:
SELECT COUNT(ReferredEmail) AS CountEmail FROM TenantReferral WHERE ReferredEmail = 'test#xyz.com'
Then change
CmdCheckEmail.Execute()
countEmail = CmdCheckEmail("CountEmail")
to
set rs = CmdCheckEmail.Execute()
countEmail = rs("CountEmail")
Also, you have a SQL injection issue with that query. You should be using parameterized queries.

CmdCheckEmail("CountEmail") tries to access the default member of the Command object, which is the parameters collection. However, you don't want to access a parameter but a field of the resulting recordset.
Try this (not tested):
Set rs=CmdCheckEmail.Execute()
countEmail = rs("CountEmail")
Apart from that, beware: This line:
CmdCheckEmail.CommandText = "SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = '" & Request("Email") & "'"
is vulnerable to an SQL injection attack.
Never embed literal strings into SQL statement; use parameters instead. (In this case, you would do that using the Command.Parameters collection.)

Related

Can't update table fields depending on value on number

So I have a form where I can select an excel file, it'll make a table which is an exact copy of that file, and then it'll try to match fields from that table with a project table and update the matching fields. The issue is sometimes the projects field won't update. As an example the existing value is 1.0319. If my excel file has 1.026 it will not update. 1.026 does appear in the temp table. But if I change it to 1.016 in the excel it will update. Then if I change it back to 1.026, it will update. However if I change it to 1.0319, the original value, it won't update. It honestly has me baffled and I wonder if it's actually a fault in access or VB. Here's the code, I simplified it a bit by removing the other fields it tests for and the excel load as that works fine.
Dim sSQL As String
Dim db As Database
Dim recTemp, recProj As Recordset
Dim intUpdatedRecordCount As Integer
Dim bUpdatedRecord As Boolean
Dim sSelectedFieldsQuery As String
sSelectedFieldsQuery = "P_Ratio"
'Update Generator data with imported table
Set db = CurrentDb()
sSQL = "SELECT TempImpProjRes.Desc, TempImpProjRes.ElemName, TempImpProjRes.BusA, TempImpProjRes.ID, TempImpProjRes.ProjID, " & _
"TempImpProjRes.ElemID, " & sSelectedFieldsQuery & " FROM TempImpProjRes"
Set recTemp = db.OpenRecordset(sSQL, dbOpenDynaset, dbConsistent)
'begin to loop over imported data
If recTemp.RecordCount > 0 Then
recTemp.MoveFirst
Do While Not recTemp.EOF
sSQL = "SELECT Projects.ProjID, Projects.ElemID,"Projects.P_Ratio FROM Projects WHERE Projects.ProjID=" & recTemp!ProjID & " AND Projects.ElemID=" & recTemp!ElemID"
Set recProj = db.OpenRecordset(sSQL, dbOpenDynaset, dbConsistent)
intUpdatedRecordCount = 0
bUpdatedRecord = False
bUpdatedRecord = Not CDbl(Format(recProj!P_Ratio, "0.00")) = CDbl(Format(recTemp!P_Ratio, "0.00"))
intUpdatedRecordCount = intUpdatedRecordCount + BooleanToInt(bUpdatedRecord)
'if any field has been updated then we need to update the respective value in the Projects table
If intUpdatedRecordCount > 0 Then
recProj.Edit
recProj!P_Ratio = CDbl(Format(recTemp!P_Ratio, "0.0000"))
recProj!Updated = Date
recProj.Update
End If
recProj.Close
Set recProj = Nothing
recTemp.MoveNext
Loop
End If
recTemp.Close
db.Close
Set recTemp = Nothing
Set db = Nothing

ASP Classic - If test failing

I really do not understand why the if test always fails. I have validated the session variable sCrs_cde (course code) is correct and exists in only one of the multiple records returned by the sql query. (It is part of a foreign key tied to year and semester). I am trying to sert the value for the course title, but it is always writing out as an empty value ('')
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_Jenz_STRING
Recordset1_cmd.CommandText = "SELECT ID_NUM, Crs_Title, YR_CDE, TRM_CDE, CRS_CDE, TRANSACTION_STS, SUBTERM_CDE FROM dbo.STUDENT_CRS_HIST WHERE ID_NUM = ? And Transaction_sts = 'C' "
Recordset1_cmd.Prepared = true
Recordset1_cmd.Parameters.Append Recordset1_cmd.CreateParameter("param1", 5, 1, -1, Recordset1__MMColParam) ' adDouble
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<%
Do While not Recordset1.Eof
response.write(Recordset1.Fields.Item("CRS_cde").Value)
IF (Recordset1.Fields.Item("CRS_cde").Value) = (Session("sCrs_cde")) THEN
Session("sCrs_Title") = (Recordset1.Fields.Item("CRS_Title").Value)
Session("sYr_cde") = (Recordset1.Fields.Item("YR_CDE").Value)
Session("sTrm_cde") = (Recordset1.Fields.Item("Trm_Cde").Value)
Session("sSubterm_cde") = (Recordset1.Fields.Item("Subterm_cde").Value)
EXIT Do
ELSE
Recordset1.movenext
END IF
Loop
Thank you everyone. I made a boneheaded mistake every programming 101 class teaches. I did not rtrim the values. I don't know where the extra spaces came from since both values were retrieved from the database (different tables), but after rtrimming both values in the if statement, I finally got it to pass.

Getting error Multiple-step operation generated error

I am debugging some old code and I am getting error on this part
rs("country code").value = NullIfBlank(Request.Form("country code"))
The error says "Multiple-step operation generated errors. Check each status value."
I tried to understand what NullIfBlank means and to my understanding, I tried to rewrite the code this way:
If rs("country code").value Is Nothing Then
rs("country code").value = Request.Form("country code")
End If
now I am not getting an error when there is a value in rs("country code").value, but I get an error in this statement
rs("country code").value = Request.Form("country code")
My whole code looks like this
if request.form("submit")="Save Changes " or request.form("submit")="Save Changes to a New " then%>
<%
id = request.form("id")
if id is nothing then id = ""
cmd1.ActiveConnection = strconn
cmd1.CommandText = "FormBlankSpecial"
cmd1.CommandType = adCmdStoredProc
cmd1.Parameters.Append (cmd.CreateParameter("#id", adVarChar, adParamInput, 50, id))
rs.CursorLocation = adUseClient
rs.LockType = adLockPessimistic
rs.open (cmd1)
if cmd1.Parameters.count > 0 then
cmd1.Parameters.delete("#id")
end if
if request.form("submit")="Save Changes to a New" then
rs.addnew
rsmax.open ("FormBlankMax", strconn, adOpenKeyset, adLockPessimistic, adCmdStoredProc)
rs("idx").value=(1*zeroif(rsmax("maxid").value))+1
end if
' rs("country code").value = NullIfBlank(Request.Form("country code"))
' I keep getting error here
If rs("country code").value Is Nothing Then
rs("country code").value = Request.Form("country code")
End If
Below is the isnull function
Public Shared Function NullIfBlank(ByVal Str)
On Error Resume Next
NullIfBlank = ""
If Str = "" Then NullIfBlank = DBNull.Value Else NullIfBlank = Str
Return NullIfBlank
End Function
and the sql stored procedure looks like this
select isnull([Country Code], '') as [Country Code]
from testTable
when I do like this in sql statement
select [Country Code] as [Country Code]
from testTable
then I don't get that error.
any help will be greatly appreciated.
You have to understand:
Nothing is a special object that indicates that a variable that should contain an object does not. While that seems similar to n/Null pointers/references in other languages, you should not think "Null" when stumbling upon "Nothing".
Assigning an object (even this Nothing) to a variable needs Set in VBScript.
Null in VBScript is a special value that indicates that a variable that should contain a value does not. This is like Null in SQL.
(There is another special value to indicate not quite decent variable content in VBScript: Empty - it differs from Null in operations/comparisons.)
Assigning a value to a variable is done without Set in VBScript.
Vour:
id = request.form("id")
if id is nothing then id = ""
seems to read a string value from a form element into id. Then id is not an object and can not be compared to the Nothing object. Or you want to access the element/object - then you must use
Set id = request.form("id")
Your
If rs("country code").value Is Nothing Then
tries to check a database column value (probably a string) to the Nothing object. Depending on your column definition the field may contain Null - then you must check for Null (not Nothing):
If IsNull( rs("country code").value) Then
You should publish the NullIfBlank() function, because "Multiple Step" errors often point to SQL problems.

Store the result of an sql query into a variable

I would like to know how I could assign the result of an SQL query to a variable.
I have the query below :
set userid = Server.CreateObject("adodb.recordset")
user = "SELECT id FROM Users WHERE UserEmail = '" & UserEmail & "'"
userid.Open query,OLSLive,1,3
and I would like to assign the result of the query so that I can pass it as a parameter to a stored procedure.
Assuming one value is expected to be returned you simply need to read the recordsets 1st value;
userid.Open query,OLSLive,1,3
if not userid.eof then 'check for rows
your_variable = userid.collect(0) 'read 1st column, 1st row
...
else
'no matching row
I'm going to guess that this is VBScript...
userID.Open query,OSLive,1,3
if not userID.eof then
variableNamedSomething = recordset("id")
else
' something else
end if
'... get rid of the connection
userID.Close
set userID = nothing
OSLive.Close
set OSLive = nothing

VB6 syntax problem, "no current record" error

I am writing an app in vb6 using sql server 2005. here is my current code.
Dim Sqlstring As String
Dim rstCurrentTicket As Recordset
Sqlstring = "Select SubmiterName, LastViewDate, Department, Description, Urgency, SubmitDate, ResolvedDate from TroubleTickets where Title ='" + Trim(TicketComboBox.Text) + "'"
Set rstCurrentTicket = cnnSel.OpenRecordset(Sqlstring)
NameText.Text = rstCurrentTicket!SubmiterName
DeptText.Text = rstCurrentTicket!Department
Me.DescriptionText = rstCurrentTicket!Description
Me.UrgencyText = rstCurrentTicket!Urgency
when I run this code i recieve an error code saying:
"Run-Time error: '3021'"
"no current record"
and it highlights this line of code:
NameText.Text = rstCurrentTicket!SubmiterName
any suggestions of how to fix this?
Your recordset has no results. You can check for this as follows:
If Not rstCurrentTicket.EOF Then
NameText.Text = rstCurrentTicket!SubmiterName
DeptText.Text = rstCurrentTicket!Department
Me.DescriptionText = rstCurrentTicket!Description
Me.UrgencyText = rstCurrentTicket!Urgency
End If
EOF = End Of File = the end of the recordset has been reached.
Keith is exactly right, but I wanted to give a little more detail
For ADO and DAO, you have a Begin-of-File marker (BOF)and an End-of-File marker(EOF). The records are returned like this
[BOF]
[Record one] <-
[Record two]
...
[Record n]
[EOF]
The arrow points to where the cursor is. The cursor points to which record in the record set that is returned.
When no records are returned, you get this
[BOF]
[EOF]
So, if both flags are set, there are no records. If EOF is set, either you have no records, or you've moved past the last record. (You move that cursor to the next record by this command.)
rstCurrentTicket.MoveNext
You can also check by
If (rstCurrentTicket.EOF and rstCurrentTicket.BOF) Then
msgbox "There were no Trouble Tickets found."
Else
'Do something here.
End If