how to protect your website against SQL injection ,

To show you how SQL Injection attacks works and how to protect your website against SQL injection , I’ve created one web application vulnerable and other that is invulnerable to SQL injection , so you’ll be able to try live example of sql injection and learn easily how to protect your web app/ sites .
SQL Injection is subset of the an unverified/unsanitized user input vulnerability and the idea is to convince the application to run SQL code that was not intended.
Here is example where we have database called users that contains Usernames and Passwords.
We use simple web app , where visitor types Username , and received Password on output for typed username.
Web app PHP Code :
$username=$_POST[“fname”];
$queryStr = “SELECT * FROM users where Username=’$username’  “;
# Output the string for debugging
echo “SQL query :”;
echo $queryStr;
# Execute the MySQL query
$result = mysql_query($queryStr) or die(‘nece ispisati greska: ‘ .mysql_error());
echo “<br>”;
while ($row = mysql_fetch_assoc($result))
{
echo “Username:” ;
echo $row[‘Username’];
echo “<br>” .  “Password:” ;
echo $row[‘Password’];
echo “<br>”;
}

If the username that was submitted is John the code will output the following query and execute it.
SELECT * FROM users WHERE Username = ‘John’
Attacker can exploit this code by injecting SQL using the submission form. In this example if you type ‘OR ‘t’=’t , you’ll received all passwords , query will be formed like this.
SELECT * FROM users WHERE Username = ” OR ‘t’=’t’
When this query is executed, it will return all the records in the database since t=t will be TRUE .
Ive created web application vulnerable to SQL Injection , so you can try it on this link: WEB SECURITY EXAMPLES

To protect your website against SQL Injection you should use function that will escape any special characters in the string to be used in a SQL statement. In PHP you can use the mysql_real_escape_string().

$username=mysql_real_escape_string($_POST[“fname”]);
$queryStr = “SELECT * FROM users where Username=’$username’  “;
# Output the string for debugging
echo “SQL query :”;
echo $queryStr;
# Execute the MySQL query
$result = mysql_query($queryStr) or die(‘nece ispisati greska: ‘ .mysql_error());
echo “<br>”;
while ($row = mysql_fetch_assoc($result)) {
echo “Username:” ;
echo $row[‘Username’];
echo “<br>” .  “Password:” ;
echo $row[‘Password’];
echo “<br>”;
}
Try to type OR ‘t’=’t’ into Web Application INVULNERABLE to SQL Injection , above . You’ll see how mysql_real_escape_string() escape any special characters

Comments