Its a very severe issue lots of low slandered websites are facing this issue.
SQL injection is a code injection technique that impose on a security vulnerability occurring in the database layer of an application.
The unsteadiness is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.
It is an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.
By this SQL injection will give a chance to hackers to login to website with out proper user details, to delete the table data or its a possibility to drop entire database. Here is a some examples of SQL injection techniques.
Below is the simple PHP program which we will use to fetch user data.
<?php
$sql = "SELECT * FROM user where user_name = '" . $_POST["username"] . "' AND password = '" . $_POST["password"] . "'";
$result = mysql_query($sql);
?>
In the form I'll submit below values
Username = testuser
password = testpassword
Then our SQL query will become as below:
SELECT * FROM user where user_name = 'testuser' AND password = 'testpassword';
This above query will execute properly with out any issues.
But I'll provide the data as below:
Username = testuser' OR 1=1;--
Password = hellostring
Now the query becomes:
SELECT * FROM user where user_name = 'testuser' OR 1=1; --' AND password = 'hellostring';
In MySQL "--" represents a comment. Query will not be executed after "--".
So my executable query becomes,
SELECT * FROM user where user_name = 'testuser' OR 1=1;
This above query will definitely returns not null result set. So hacker can login in automatically.
If hacker knows database table name or database name then hacker can simply drop the data.
I'll simply enter the values as below:
Username = testuser' OR 1=1; drop table user; --
Password = dummydata
Now our query will become:
SELECT * FROM user where user_name = 'testuser' OR 1=1; drop table user; --' AND password = 'dummydata';
";" is a statement terminator in MYSQL. So first two queries will be executed with one instance and our user table will be dropped.
How to prevent SQL injection:
SQL Injection will be solved if we handle single quote and/or double quote in parameter values. We need to escape those quotes. For that simply we need to replace "'" with "\'" and '"' with '\"'. Then there won't be any issues with SQL injection.
In PHP we are having built in function to escape single quotes: mysql_real_escape_string
This fuction will add a backslash before single quote in the passed parameter.
So your select query must be in the below mentioned pattern:
<?php
$sql = "SELECT * FROM user where user_name = '" . mysql_real_escape_string($_POST["username"]) . "' AND password = '" . mysql_real_escape_string($_POST["password"]) . "'";
$result = mysql_query($sql);
?>