Click here to Skip to main content
14,739,811 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Dear all, Please help


in my web application i get some datas from user through text box.
i store the text box value in a variable and insert into database.


but when the user enters some characters like ',;,: in text box that show error how can i solve it.


for examle:anoop's,kira's etc.
Posted

I assume that you are using a simple SQL query such as
SqlCommand cmd = new SqlCommand("INSERT INTO tab (field1) VALUES (" + textBox1.Text + ")");
And the database complains?

Congratulations! This is leaving an opening known as "SQL Injection".

The addition of special characters causes the database to process them as part of a command. For example (DO NOT DO THIS) if you enter "hello);DROP TABLES tab" into your text box, the SQL would see:
"INSERT INTO tab (field1) VALUES (hello);DROP TABLES tab;)"
as a single command.
Because ';' is a statement terminator, SQl sees this as two commands: An INSERT, followed by a DROP TABLES. It inserts your name as "hello", and then deletes the tab table.

Don't do it this way. Use a parameterized query:
SqlCommand cmd = new SqlCommand("INSERT INTO tab (field1) VALUES (@NAME)");
cmd.AddWithValue("@NAME", textBox1.Text);

And you problem will disappear, instead of your tables...
   
You can define a regular expresssion to defined what is either acceptable (generally more thorough) or unacceptable.
Depending on the technology used (you don't say whether this ASP.NET, Winforms or WPF) you will need to use the regex in the relevant validator to prevent the user continuing before the input is corrected.

You should also check the input before insertion and reject if not valid, and pass the value as an SQL parameter to stop SQL injection attacks.
   
what is the data type of variable?????
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900