Last time we discuss the simplest logic behind the SQL injection. Even though it looks like simple it can do a real damage to your website and its valuable data. If you are a webmaster or blogmaster you can follow this simple rules to prevent your website been attacked by SQL injection.
Validate user input
Always remember to validate user input before it send to the SQL query. Always check whether user enters special characters (= ' ') or key words from scripts. You should apply user input validation for all the user input. Any of the user
couple of good website tutorial teach you how to validate.
Validating user input in PHP - Nice tutorial explain the importance of user input validation. Tutorial start from 'Never trust user input' and go throught basic PHP validation methods.
Secure your web applications by validating user input ith PHP is another short but nicely explained tutorial explains couple of basic user input validations.
msdn user input validations in asp.net tutorial explains basic asp.net validation for login page.
Regular Expressions is handy way to vlidate user input.
Change your SQL queries style.
First Style: Select * from USERS where USERNAME = ' + usernametxt.Text + ' AND PASSWORD = ' + passwordtxt.Text +';
Second Style:
SqlCommand sc = new SQLCommand("Select * from USERS where USERNAME = @username AND PASSWORD = @password;", myconnection);
sc.Parameters.AddWithValue("@username", usernametxt.Text);
sc.Parameters.AddWithValue("@password", passwordtxt.Text);
If you are following the first style you should change it to the second style. In first style support SQL injection as it creates new SQL query with the user input, where in second method it always take it as a value (string , integer) and assign it to the parameter. It never create a new SQL query with the user input.
This is two major steps you can take to stop SQL injection.
Related Reading