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.
Figure 1
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.
Figure 2
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.
Figure 3
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.
Figure 4
It complains the single quote problem (here mySQL version is 5.0.51b)
So a complete working login in PHP might look like this.
Figure 5
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
Figure 6
Now let’s have a look on how to do SQL injection and prevent that.
Important :
You can directly put the PHP variables inside a string. Example :
$var = “thuruinhttp”;
$sql = “SELECT * FROM Table WHERE Url = ‘$var'”;
echo $sql;
Here the echo output would be
SELECT * FROM Table WHERE Url = ‘thuruinhttp’
But when you put it directly with $_POST[] it makes a contradiction.
Hey Great post! Thanks for posting it!
hello
In the production the login code varies much compared to the above code.
Here the above example is used only to explain the SQL Injection mechanisms.