简体   繁体   中英

In SQL, how to retrieve data of a certain record by whatever User Inputs in the text box. How to send user input variable to the SQL Statement

I have simple HTML code which is

form method="post" action='Data.asp

and

input type="text" name="UserInputData" size=20

What I want is that whatever user inputs in the text box should be stored into a variable in the Data.asp page which I assume will be something like this:

<%
  ScriptUserInputData=request("UserInputData")
%>

now on Data.asp I also have the select statement as the following:

select * from Data;

On the html interface, when I click on the submit button with or without typing in anything in the text box, it shows all the records that exist in Data table which means that it is connecting to the database successfully, I now want to know how to display records from this Data table according to what the user inputs in the text box. I did a lot of research but I cannot find it at all. I tried lots of different ways such as Select * from Data WHERE Column1=UserInputData .

In simple words, I just want to pass the user input value to the select query which is then sent off to the database to get the output if the certain column or row contains of that value which user had input etc.

I'm new to VBScripting and SQL. Please help me with it. It took me quite a long time to write all this information for you to understand properly too.

The simplest way (not the best way) is to do it like such:

<%
  ScriptUserInputData=request("UserInputData")
  sql = "select * from Data" 
  if ScriptUserInputData <> "" then
     sql = sql + " WHERE Column1 = '" + Replace(ScriptUserInputData,"'","''") + "'"
  end if
%>

Now the above is highly vulnerable to SQL Injection and you should really be using parameterized queries instead. Something like such:

Set cmd = server.createobject("ADODB.Command")

cmd.ActiveConnection = yourconnection 
cmd.CommandText = "select * from Data WHERE Column1 = ?"
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900 

set prm = cmd1.CreateParameter("@prm", 200, 1, 200, ScriptUserInputData )
cmd.Parameters.Append prm

The above is just an example, but should get you going in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM