Simply SQL Injection is known as putting some malicious SQL statements as standard user input and makes the system to perform an unintended operations.
This article will give you an idea of SQL Injection and how it can be eliminated.
In a typical login let’s assume the table Users have the below data.
Let’s create a simple login in PHP (Version 5) The below login has an error. I did this here because to give a clear idea of how PHP 5 works.
When we type the above statement and run the file under Apache it shows this error.
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\SQL\index.php on line 9
The error is at $sql variable. Because here using $_POST within the double quotes is possible only when you do not specify the single quote for accessing the variable values. You can simply guess the reason because the double quotes and the single quotes both are used to represent the string literals. So the above statement is a mess.
The following is a valid PHP variable assignment. But still this not going to work because the mySQL server expects its varchar arguments within the single quotes. Here our username and the password are varchar types.
Let’s check this out. Here’s the login page display with Figure 3 $sql variable.
When I type the Username as admin and the password as 123 the $sql will appear as
SELECT * FROM Users WHERE username = admin AND password = 123
When we execute this in the mySQL server.
It complains the single quote problem (here mySQL version is 5.0.51b)
So a complete working login in PHP might look like this.
So now try an authenticated login using admin and 123
The statement look like this
SELECT * FROM Users WHERE username =’admin’ AND password =’123′
When executed against the database, the result is
Now let’s have a look on how to do SQL injection and prevent that.
You can directly put the PHP variables inside a string. Example :
$var = “thuruinhttp”;
$sql = “SELECT * FROM Table WHERE Url = ‘$var'”;
Here the echo output would be
SELECT * FROM Table WHERE Url = ‘thuruinhttp’
But when you put it directly with $_POST it makes a contradiction.