Hello Guys, SQL is a query which helps the app to talk to the database.
SQL Injection is injection technique that hacker uses to attack websites, by inserting malicious SQL statements into webpage input(like user inputs fields). With the help of SQL injection a hacker could completely ruin one’s database.
This kind of attacks allows to spoof the identity and tamper the existing data and changing it. It allows complete disclosure of all data on the system, and the attacker could take over the database completely SQL injection is very common with PHP, ASP application, J2EE and ASP.NET application are less prone to these kind of attacks.
I will first show you some example’s of SQL injection.
UserId= getRequestString("id"); txtSQL = "SELECT * FROM Users WHERE id = " + UserId;
Above example purpose is to create a SQL statement to select a user with the given id.
If there is no validation to the user input then the user could input something like:
txtSQL = "SELECT * FROM Users WHERE id = '105 OR 1=1';
Above SQL statement is valid and will return all row’s from table ‘Users’, since 1=1 is always true.
Here are some steps to prevent SQL injection:
Sanitize the input data by checking for known good data by validating for type,length,format and range.
Use type-safe SQL parameters can be used for stored procedures or dynamically constructed SQL command strings. SqlParameterCollection provide type checking and length validation. Using this parameters, input is treated as literal value and not an executable code.
Only selected stored procedures in database should be accessible and no direct table access should be provided.
Do not disclose the error message to the user in case of database errors.
In case of PHP you can use prepared statement it also helps prevent the SQL injection Prepared Statements do not combine variables with SQL strings, so it is not possible for an attacker to modify the SQL statement. Prepared Statements combine the variable with the compiled SQL statement, this means that the SQL and the variables are sent separately and the variables are just interpreted as strings, not part of the SQL statement.
Example of Prepared Statement :
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
For Full code visit W3Schools