I need to insert some data into DB, there is a problem..it gives me an error :
Source line:
SET sql ="Insert Into Products (ProductName,SupID,CatID,Price,Pic,Description) Values( '"&pName&"','"&pbId&"','"&pcId&"','"&price&"','"&pic&"','"&desc&"')"
Description: Object required: '[string: "Insert Into Products"]'
I dont understand what he wants..
This is my code:
dim sql
dim price
dim desc
dim pName
dim pcId
dim pbId
dim pic
set pic = Request.Form("picUpload")
set desc = Request.Form("tbDescProduct")
set price= Request.Form("tbPriceProduct")
set pcId =Request.Form("ddlCategoryForProd")
set pbId =Request.Form("ddlBrandForProd")
set pName=Request.Form("tbProductName")
IF((bName<>"")AND(desc<>"")AND(price<>"")AND(pcId<>"-1")AND(pbId<>"-1")AND (pic<>"")) THEN
set con = Server.CreateObject("ADODB.Connection")
con.open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("WebData/DB.mdb") & ";"
set rs = con.Execute("Select * FROM Products WHERE ProductName = '"&pName&"' and mode= true")
IF rs.EOF = true then
SET sql ="Insert Into Products (ProductName,SupID,CatID,Price,Pic,Description) Values( '"&pName&"','"&pbId&"','"&pcId&"','"&price&"','"&pic&"','"&desc&"')"
SET rs =con.Execute(sql)
response.write("<script language=""javascript"">alert('Product added succesfully!');</script>")
ELSE
response.write("<script language=""javascript"">alert('Product already exist!');</script>")
END IF
'END IF
In VBScript, VBA and VB5/6, SET is required to assign an object reference; to assign any other sort of data (including a string), just remove it:
sql = "Insert Into Products (ProductName,SupID,CatID,Price,Pic,Description) Values( '"&pName&"','"&pbId&"','"&pcId&"','"&price&"','"&pic&"','"&desc&"')"
(In VBA and VB5/6 you could also use LET here.)
The reason SET works when assigning the result of a Request.Form("foo") call is because the Form collection is a collection of objects - the subsequent tests against "" and "-1" are valid only because the objects returned have a default parameterless property or method that return a string-compatible variant.
If I was to guess I'd say your problem is you're passing the SupID and CatID fields as strings when they are probably integers. The problem with handling INSERT this way is you leave yourself open to SQL Injection plus you encounter data type issues like you seem to be experiencing here.
Whenever possible when interacting with a database you should try to use Parameterised Queries. In Classic ASP the best object to do this is ADODB.Command.
Here is an example using your code;
NOTE: If you have problems with the ADO named constants like adParamInput then look in the links section below to see how to use the METADATA tag in your global.asa file to reference the ADO type library across your application.
Dim cmd, sql, conn_string, rs, data
'Wouldn't recommend storing your database inside your website root, instead
'store it outside in another folder and set up a variable in an include file
'to store the location. That way it is not accessible to everyone.
conn_string = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("WebData/DB.mdb") & ";"
Set cmd = Server.CreateObject("ADODB.Command")
sql = "SELECT * FROM Products WHERE ProductName = ?"
With cmd
.ActiveConnection = conn_string
.CommandType = adCmdText
.CommandText = sql
Call .Parameters.Append(.CreateParameter("#ProductName", adVarWChar, adParamInput, 50))
Set rs = .Execute(, Array(pName))
If Not rs.EOF Then data = rs.GetRows()
Call rs.Close()
Set rs = Nothing
End With
If IsArray(data) Then
sql = ""
sql = sql & "INSERT INTO Products (ProductName, SupID, CatID, Price, Pic, Description) " & vbCrLf
sql = sql & "VALUES (?, ?, ?, ?, ?, ?)"
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = conn_string
.CommandType = adCmdText
.CommandText = sql
'Define Parameters
'Making some assumptions about your data types, but you can modify these to fit
'good guide for this is http://www.carlprothman.net/Technology/DataTypeMapping/tabid/97/Default.aspx
Call .Parameters.Append(.CreateParameter("#ProductName", adVarWChar, adParamInput, 50))
Call .Parameters.Append(.CreateParameter("#SupID", adInteger, adParamInput, 4))
Call .Parameters.Append(.CreateParameter("#CatID", adInteger, adParamInput, 4))
Call .Parameters.Append(.CreateParameter("#Price", adCurrency, adParamInput, 4))
Call .Parameters.Append(.CreateParameter("#Pic", adVarWChar, adParamInput, 255))
Call .Parameters.Append(.CreateParameter("#Description", adLongVarWChar, adParamInput, 1000))
'Some of your variables may require conversion before setting the parameter values.
.Parameters("#ProductName").Value = pName
.Parameters("#SupID").Value = CLng(pbId)
.Parameters("#CatID").Value = CLng(pcId)
.Parameters("#Price").Value = price
.Parameters("#Pic").Value = pic
.Parameters("#Description").Value = desc
'Execute Command
.Execute()
End With
Set cmd = Nothing
Call Response.write("<script language=""javascript"">alert('Product added succesfully!');</script>")
Else
Call Response.Write("<script language=""javascript"">alert('Product already exist!');</script>")
End If
Links
Data Type Mapping
Using METADATA to Import DLL Constants
Answer from SQL insert into database with apostrophe
Related
I'm trying to use the parameterizartion to prevent SQL injection in one of the textbox in the HMI I working with.
Have looked a lot for a solution what I gathered is depending on what SQL syntax there is I can use either ? or # to tell the system that is parameter but both of them are throwing an error.
Dim DBCommand
Dim DBRecordSet
Dim Connection
Dim sqlString
Set DBRecordSet = CreateObject("ADODB.Recordset")
Set DBCommand = CreateObject("ADODB.Command")
Set Connection = GetDBConnection("Test")
sqlString = "Insert into [WorkCommentLog] (Worklog_WorkID, Comment,
InsertTime, WrittenBy) values" &_
"('"& WorkID &"' , #Comm , GetDate() , '" & User.Value &"');"
DBCommand.Parameters.Append DBCommand.CreateParameter ("#Comm",
adVarChar, adParamInput, 255, WinCC_Comment.Value)
DBCommand.CommandText = sqlString
DBCommand.Execute(adExecuteNoRecords)
Connection.Close
Dim DBCommand
Dim DBRecordSet
Dim Connection
Dim sqlString
Set DBRecordSet = CreateObject("ADODB.Recordset")
Set DBCommand = CreateObject("ADODB.Command")
Set Connection = GetDBConnection("Test")
sqlString = "Insert into [WorkCommentLog] (Worklog_WorkID, Comment, InsertTime, WrittenBy) values" &_
"('"& WorkID &"' , ? , GetDate() , '" & User.Value &"');"
DBCommand.Parameters.Append DBCommand.CreateParameter ("Comment", adVarChar, adParamInput, 255, WinCC_Comment.Value)
DBCommand.CommandText = sqlString
DBCommand.Execute(adExecuteNoRecords)
Connection.Close
The first code snippet throws this error:
Must declare the scalar variable "#Com"
while the second code snippet throws this error:
No Value given for one or more required parameters
I have found that executing a parametrized query using VBScript like so has always worked for me:
Set command = CreateObject("ADODB.Command")
Set command.ActiveConnection = Connection
command.CommandText = "sp0001_ExampleStoredProcedure" ' The name of the stored procedure in my database that has the parametrized query.
command.CommandType = 4
command.Parameters("#Parameter1") = "parameterValue"
command.Parameters("#Parameter2") = "parameterValue"
command.Execute
Note that this example is executing a parametrized stored procedure in my database.
You could try writing your insert query into a stored procedure in your database instead of hard-coding your query in the VBScript file.
I have a database and MSSQL code in vbscript:
Dim conn, SQL, rs
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=DJ-PC;Initial Catalog=Baza_NC;user id ='user_baza_nc';password='Password1'"
Set myConn = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command" )
myConn.Open DB_CONNECT_STRING
Set myCommand.ActiveConnection = myConn
myCommand.CommandText = "UPDATE Klienci_NC SET Klienci_NC.Klient = '" & Klient_niceform & "' WHERE Klienci_NC.ID = '" & ID_zmienna & "'"
myCommand.Execute
myConn.Close
When I use the ID with the participation of a txt file as a counter to work well.
The problem appeared when I wanted to use the MSSQL database autoincremant.
I need a string variable to the variable & ID_zmienna &
How to get a string variable with the ID field from the database?
Not sure why you are trying to call an INT data type in SQL as a VARCHAR.
The query should be
myCommand.CommandText = "UPDATE Klienci_NC SET Klienci_NC.Klient = '" & Klient_niceform & "' WHERE Klienci_NC.ID = " & ID_zmienna
you only pass ' for string data types in SQL Server, integers are just
[column] = int_value
Having said all that you should be passing the parameters in the .Parameters collection of the ADODB.Command object rather than specifying them directly in the SQL query string. As it stands the page is open to SQL Injection attack and also means you have to handle not passing ' when dealing with INT and escaping extra ' in strings etc., which just isn't necessary.
Dim SQL, myCommand
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=DJ-PC;Initial Catalog=Baza_NC;user id=user_baza_nc;password=Password1"
'Most ADO providers expect a `?` to denote where a parameter is expected.
SQL = "UPDATE Klienci_NC SET Klienci_NC.Klient = ? WHERE Klienci_NC.ID = ?"
Set myCommand = CreateObject("ADODB.Command" )
With myCommand
'No need for ADODB.Connection object ADODB.Command can create one from the
'Connection String.
.ActiveConnection = DB_CONNECT_STRING
.CommandType = adCmdText
.CommandText = SQL
'Define parameters in order they appear in the query.
Call .Parameters.Append(.CreateParameter("#klient", adVarWChar, adParamInput, 50))
Call .Parameters.Append(.CreateParameter("#id", adInteger, adParamInput, 4))
'Only running an update statement so no need to return a
'ADODB.Recordset.
Call .Execute(, Array(Klient_niceform, ID_zmienna), adExecuteNoRecords)
End With
'Release the object from memory
Set myCommand = Nothing
Useful Links
Assuming you are using Classic ASP with VBScript
Using METADATA to Import DLL Constants (if you are having problems with the ADO constants like adCmdText, adInteger etc., being undefined this will help)
Otherwise you will need to define the ADO constants yourself like so;
Const adCmdText = 1
Const adInteger = 3
Const adVarWChar = 202
Const adParamInput = 1
Const adExecuteNoRecords = &H00000080
I am creating one login validation page for my classic asp site(vbscript). as I want prevent my page from SQL Injection, I used parametrized queries in my page but I am unable to retrieve value after writing if Not Recordset.EOF line. value is not passing. please help me to solve this issue. my code is below;
<%
Dim Objrs, objConn, objCmd, str
Set objConn = Server.CreateObject("ADODB.Connection")
Set objCmd = Server.CreateObject("ADODB.Command")
Set Objrs = Server.CreateObject("ADODB.Recordset")
objConn.open MM_connDUdirectory_STRING '(already created)
Set objCmd.ActiveConnection = objConn
str = "SELECT * FROM admin WHERE Ausr=? AND Apwd=?"
objCmd.CommandText = str
objCmd.CommandType = adCmdText
dim objParam1, objParam2
Set objParam1 = objCmd.CreateParameter("param1", adVarChar, adParamInput, len(StrUserName), "")
objCmd.Parameters.Append objParam1
objCmd.Parameters("param1") = StrUserName
Set objParam2 = objCmd.CreateParameter("param2", adVarChar, adParamInput, len(StrPassword), "")
objCmd.Parameters.Append objParam2
objCmd.Parameters("param2") = StrPassword
set objRS = objCmd.execute
'if objRS.EOF <> True and objRS.BOF <> True then
'if Objrs("Ausr") = objCmd.Parameters("param1") then
'response.Write(Objrs("Ausr"))
'response.Write should show username but its showing blank
'end if
'end if
'Do While Not objRS.EOF
'if Objrs("Ausr") = objCmd.Parameters("param1") then
'response.Write(Objrs("Ausr"))
'end if
'objRS.MoveNext
'Loop
If Not objRS.EOF Then
response.write("Granted access to the user:" & StrUserName)
end if
%>
I tried with If..End If as above but its showing same problem, the recordset(objrs) parametrized method is not executing. its show me blank page. code should check if user exist or not. Response.Write("Granted access to the user:" & StrUserName) should show me strusername value but its not showing and page is blank. please help me workout where I'm going wrong?
From i can see with you current code,you have 2 problems:
You have this condition if objRS.EOF <> True and objRS.BOF <> True then with this you are excluding the first and the last record from printing. Don't know why this is needed, but because you are not iterating over all the elements in your recordset (aka Rows). you will never see any record printed.
To overcome the problem #1 you need to enclose all the code in loop (for,while,do while) and use objRS.MoveNext() function in your recordset object to read all the records obtained in your Query.
this is all the problems that i can see with this limited context. I hope this helps.
More Information: Recordset Object Properties, Methods, and Events - MSDN
EDIT: Seeing the edit from OP in the code, and the goal that i think he want to achieve i suggest this code instead:
'Do While Not objRS.EOF'
'if Objrs("Ausr") = objCmd.Parameters("param1") then'
'response.Write(Objrs("Ausr"))'
'end if'
'objRS.MoveNext'
'Loop'
If Not objRS.EOF Then
response.write("Granted access to the user:" & StrUserName)
End if
I'm assuming that you want to check if a single user its logged in.
Debug; Check if you are passing the values to the parameters. Print out the values and see.
Response.write "StrUserName ="& StrUserName &"<br/>"
Response.write "StrPassword ="& StrPassword &"<br/>"
set objRS = objCmd.execute
Also, try passing in the values during creation of the parameter:
Set objParam1 = objCmd.CreateParameter("param1", adVarChar, adParamInput, len(StrUserName), StrUserName)
Actually after looking closer at your code there a few issues
Didn't notice it at first but looks as though your not setting the values correctly, there are two ways to do it;
Specify them during the CreateParameter() method
Call .Parameters.Append(.CreateParameter("param1", adVarChar, adParamInput, 50, StrUserName)
Call .Parameters.Append(.CreateParameter("param2", adVarChar, adParamInput, 50, StrPassword)
Specify after creation of the parameters
Call .Parameters.Append(.CreateParameter("param1", adVarChar, adParamInput, 50)
Call .Parameters.Append(.CreateParameter("param2", adVarChar, adParamInput, 50)
.Parameters("param1").Value = StrUserName
.Parameters("param2").Value = StrPassword
That present your setting the parameter object to a string, which won't give the expected result.
Give this a try;
<%
Dim objRS, objCmd, str
Set objCmd = Server.CreateObject("ADODB.Command")
Set Objrs = Server.CreateObject("ADODB.Recordset")
str = "SELECT * FROM admin WHERE Ausr=? AND Apwd=?"
With objCmd
'No need to create ADODB.Connection as the ADODB.Command will do it
'for you if you pass the Connection string.
.ActiveConnection = MM_connDUdirectory_STRING
.CommandText = str
.CommandType = adCmdText
'Don't pass blank values, just specify the name, data type,
'direction and length.
Call .Parameters.Append(.CreateParameter("param1", adVarChar, adParamInput, 50)
Call .Parameters.Append(.CreateParameter("param2", adVarChar, adParamInput, 50)
'If setting values after the CreateParameter() don't use blank strings in
'the CreateParameter() call.
.Parameters("param1").Value = StrUserName
.Parameters("param2").Value = StrPassword
Set objRS = .Execute()
If Not objRS.EOF Then
Call Response.Write("Granted access to the user:" & StrUserName)
End If
End With
Set objCmd = Nothing
%>
Useful Links
Using Stored Procedure in Classical ASP .. execute and get results - Show how to use ADODB.Command and also return a ADODB.Recordset and convert it to an Array.
In the vb script I have a select statement I am trying to pass a string value with an undetermined length to a SQL in operator the below code works but allows for SQL injection.
I am looking for a way to use the ADO createParameter method. I believe the different ways I have tried are getting caught up in my data type (adVarChar, adLongChar, adLongWChar)
Dim studentid
studentid = GetRequestParam("studentid")
Dim rsGetData, dbCommand
Set dbCommand = Server.CreateObject("ADODB.Command")
Set rsGetData = Server.CreateObject("ADODB.Recordset")
dbCommand.CommandType = adCmdText
dbCommand.ActiveConnection = dbConn
dbCommand.CommandText = "SELECT * FROM students WHERE studentID in (" & studentid & ")"
Set rsGetData = dbCommand.Execute()
I have tried
Call addParameter(dbCommand, "studentID", adVarChar, adParamInput, Nothing, studentid)
which gives me this error
ADODB.Parameters error '800a0e7c'
Problems adding parameter (studentID)=('SID0001','SID0010') :Parameter object is improperly defined. Inconsistent or incomplete information was provided.
I have also tried
Call addParameter(dbCommand, "studentID", adLongVarChar, adParamInput, Nothing, studentid)
and
Dim studentid
studentid = GetRequestParam("studentid")
Dim slength
slength = Len(studentid)
response.write(slength)
Dim rsGetData, dbCommand
Set dbCommand = Server.CreateObject("ADODB.Command")
Set rsGetData = Server.CreateObject("ADODB.Recordset")
dbCommand.CommandType = adCmdText
dbCommand.ActiveConnection = dbConn
dbCommand.CommandText = "SELECT * FROM students WHERE studentID in (?)"
Call addParameter(dbCommand, "studentID", adVarChar, adParamInput, slength, studentid)
Set rsGetData = dbCommand.Execute()
both of these options don't do anything... no error message and the SQL is not executed.
Additional information:
studentid is being inputted through a HTML form textarea. the design is to be able to have a user input a list of student id's (up to 1000 lines) and perform actions on these student profiles. in my javascript on the previous asp I have a function that takes the list and changes it into a comma delimited list with '' around each element in that list.
Classic ASP does not have good support for this. You need to fall back to one of the alternatives discussed here:
http://www.sommarskog.se/arrays-in-sql-2005.html
That article is kind of long, but in a good way: it's considered by many to be the standard work on this subject.
It also just so happens that my preferred option is not included in that article. What I like to do is use a holding table for each individual item in the list, such that each item uses an ajax request to insert or remove it from the holding table the moment the user selects or de-selects it. Then I join to that table for my list, so that you end up with something like this:
SELECT s.*
FROM students s
INNER JOIN studentSelections ss on s.StudentID = ss.StudentID
WHERE ss.SessionKey = ?
What does your addParameter() function do? I don't see that anywhere in your code.
You should be able to create and add your string param like so:
With dbCommand
.Parameters.Append .CreateParameter(, vbString, , Len(studentid), studentid)
End With
(Small hack here. vbString has the same value as adBSTR. You'll find that the VarType of all VB "types" have matching ADO counterparts.)
Type VarType (VBScript) DataTypeEnum (ADO) Value
--------- ------------------ ------------------ -----
Integer vbInteger adSmallInt, 2-byte 2
Long vbLong adInteger, 4-byte 3
Single vbSingle adSingle 4
Double vbDouble adDouble 5
Currency vbCurrency adCurrency 6
Date vbDate adDate 7
String vbString adBSTR 8
Object vbObject adIDispatch 9
Error vbError adError 10
Boolean vbBoolean adBoolean 11
Variant vbVariant adVariant 12
Byte vbByte adUnsignedTinyInt 17
Edit: Looks like Joel has a good solution for you. I didn't realize IN isn't compatible with ADO parameterized queries. I think something like the following would work, but you probably wouldn't want to do it with (potentially) 1000 ID's.
' Create array from student IDs entered...
a = Split(studentid, ",")
' Construct string containing proper number of param placeholders. Remove final comma.
strParams = Replace(String(UBound(a) - 1, "?"), "?", "?,")
strParams = Left(strParams, Len(strParams) - 1)
With dbCommand
.CommandText = "select * from students where studentID in (" & strParams & ")"
Set rsGetData = .Execute(, a)
End With
Using IN with a Parameterised Query isn't Hard
Posting this here in relation to another question that was marked as a duplicate of this one.
This isn't as difficult as you think, the adCmdText query just needs to the placeholders in the query to match the number of parameters and their ordinal position and it will work with any number of parameters you pass into an IN statement.
Here is a quick example using the AdventureWorks example database in SQL Server. We use an Array to store the id of each Person.Contact record we wish to filter out using IN than build the parameters dynamically based on that array before executing the ADODB.Command.
Note: The source of the array is not important it could be a string list which is Split() into an Array or just an Array() call (like the one used in this example).
<%
Option explicit
%>
<!-- #include virtual = "/config/data.asp" -->
<%
Dim cmd, rs, sql, data, rows, row
'Our example parameters as an Array for the IN statement.
Dim ids: ids = Array(2, 5, 10)
Dim id
sql = ""
sql = sql & "SELECT [FirstName], [LastName] " & vbCrLf
sql = sql & "FROM Person.Contact " & vbCrLf
sql = sql & "WHERE [ContactId] IN (?, ?, ?) " & vbCrLf
sql = sql & "ORDER BY [LastName], [FirstName]" & vbCrLf
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = conn_string
.CommandType = adCmdText
.CommandText = SQL
'Loop through the Array and append the required parameters.
For Each id in ids
Call .Parameters.Append(.CreateParameter("#id" & id, adInteger, adParamInput, 4))
.Parameters("#id" & id).Value = id
Next
Set rs = .Execute()
'Output the Recordset to a 2-Dimensional Array
If Not rs.EOF Then data = rs.GetRows()
Call rs.Close()
End With
Set cmd = Nothing
If IsArray(data) Then
rows = UBound(data, 2)
For row = 0 To rows
Call Response.Write("<p>" & data(0, row) & " " & data(1, row) & "</p>" & vbCrLf)
Next
End If
%>
Output:
<p>Catherine Abel</p>
<p>Pilar Ackerman</p>
<p>Ronald Adina</p>
Worth noting this example shows the explicit way of writing the parameter code for an elegant approach to the problem see the second solution in #Bond's answer.
After reading through the article that was provided by Joel and the answer that All Blond provided this is the solution that ended up working for me.
Dim studentid
studentid = GetRequestParam("studentid")
Dim splitStudentid, x
splitStudentid = Split(studentid,",")
for x=0 to Ubound(splitStudentid)
Dim rsGetData, dbCommand, originSID
Set dbCommand = Server.CreateObject("ADODB.Command")
Set rsGetData = Server.CreateObject("ADODB.Recordset")
dbCommand.CommandType = adCmdText
dbCommand.ActiveConnection = dbConn
dbCommand.CommandText = "SELECT * FROM students WHERE studentID=?"
Call addParameter(dbCommand, "studentID", adVarChar, adParamInput, 35, splitStudentid(x))
Set rsGetData = dbCommand.Execute()
If (NOT rsGetData.EOF) Then
originSID = rsGetData.Fields(0)
//additional code
End If
next
I found that there was no elegant way to use the "in" operator in my code.
I also decided against a Stored Procedure as it is a simple query though I agree
ALSO I realize that addParameter is a Function my company uses internally so below is an additional solution that works also works but is not my companies preference.
Dim studentid
studentid = GetRequestParam("studentid")
Dim splitStudentid, x
splitStudentid = Split(studentid,",")
for x=0 to Ubound(splitStudentid)
Dim rsGetData, dbCommand, originSID
Set dbCommand = Server.CreateObject("ADODB.Command")
Set rsGetData = Server.CreateObject("ADODB.Recordset")
dbCommand.CommandType = adCmdText
dbCommand.ActiveConnection = dbConn
dbCommand.CommandText = "SELECT * FROM students WHERE studentID=?"
Set rsGetData = dbCommand.Execute(, Array(splitStudentid(x)))
If (NOT rsGetData.EOF) Then
originSID = rsGetData.Fields(0)
//additional code
End If
next
Try to add to your code following(assuming that StudentID is numeric)
dim outputArray,x,compareArray
outputArray=split(inputText,",")
for each x in outputArray
If IsNumeric(x) Then
if len(compareArray)>1 and cInt(x)>0 then
compareArray=compareArray&"," & cInt(x)
else
compareArray=cInt(x)
end if
else
' throw some log entry or do something for you to know that someone try
end if
next
and then do all your Db connection set etc up to this point where you use this new string of integers:
dbCommand.CommandText = "SELECT * FROM students WHERE studentID in (" & compareArray &")"
and this will safeguard you from anyone use your StudentId list for SQL injection. I would rather use Store procedure and user-defined table types but ...
In any case if it is not numeric then it must have some parameter like length or complexity which you can use to verify that value has not been compromised using regular expression for example for limiting what can be in that value; but idea of the looping through and verifying values remain the same.
I am having trouble when I try to introduce alphanumeric characters into ms-access database. I am able to do it with numerical and date characters, but it seems to be a problem with alphanumerical ones,
Here is the code I use:
Dim adoCon
Dim strSQL
Set adoCon=Server.CreateObject("ADODB.Connection")
adoCon.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("basededades.mdb")
'Here I am getting all the values previously passed by a form.
stringEntrada=Request.Form("stringEntrada")
stringSortida=Request.Form("stringSortida")
valoridHabitaciolliure=Request.Form("valoridHabitaciolliure")
numeropersones=Request.Form("numeroPersones")
nom=Request.Form("nom")
dni=Request.Form("dni")
tlf=Request.Form("tlf")
mail=Request.Form("mail")
ciutat=Request.Form("ciutat")
tipusH=Request.Form("tipusH")
diaReserva=Request.Form("diaReserva")
mail,nom,ciutat,tipusH,dni,valoridHabitaciolliure are alphanumerical characters from a text input form.
diaReserva,stringSortida,stringEntrada, are dates form a text input form.
tlf is a integer variable.
strSQL="INSERT INTO Reserva (dni,tlf,diaReserva,inici,fi,tipusHabitacio) VALUES ("&dni&","&tlf&",'"&diaReserva&"','"&stringEntrada&"','"&stringSortida&"'," "&tipusH&")"
adoCon.Execute(strSQL)
When I see the values inserted into the database I realise that the date variables like "diaReserva" or "stringSortida" and the numerical ones like "tlf" are inserted correctly.
To insert date variables I use a simple ' surrounded by double " in the sql query: '"&stringEntrada&"'
To insert numerical ones I only use the double: "&tlf&"
If I try to use simple ' when I am trying to insert an alphanumerical, like: '"mail"' I do not recieve any error, but the database records a blank value.
If I try to use double ", like: "mail" I am getting an error.
How I could insert alphanumerical variables without having trouble?
Thank you for your time, and sorry for my bad english.
You can avoid your "quoting problem" and also avoid SQL Injection vulnerabilities by using a parameterized query similar to this one:
Dim con '' As ADODB.Connection
Dim cmd '' As ADODB.Command
Dim stringName, longSponsorID, datetimeDateJoined
Const adCmdText = 1
Const adVarWChar = 202, adInteger = 3, adDate = 7
Const adParamInput = 1
'' test data
stringName = "Gord"
longSponsorID = 5
datetimeDateJoined = Now
Set con = CreateObject("ADODB.Connection")
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Public\mdbTest.mdb;"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = adCmdText
cmd.ActiveConnection = con
cmd.CommandText = _
"INSERT INTO Members " & _
"(memberName, sponsorID, dateJoined) " & _
"VALUES " & _
"(?, ?, ?)"
'' parameter for [memberName]
cmd.Parameters.Append cmd.CreateParameter("?", adVarWChar, adParamInput, 255, stringName)
'' parameter for [sponsorID]
cmd.Parameters.Append cmd.CreateParameter("?", adInteger, adParamInput, , longSponsorID)
'' parameter for [dateJoined]
cmd.Parameters.Append cmd.CreateParameter("?", adDate, adParamInput, , datetimeDateJoined)
cmd.Execute
Set cmd = Nothing
con.Close
Set con = Nothing