How to fix SQL Injections

When programming in PHP it is essential to use the PDO module due to the fact it offers support for prepared statements across vast databases. Also the use of outdated MySqL modules should be avoided for instance anything below PHP 5 is not to be used.

Secure Usage




$oDB=new PDO('... your connection details... ');
$hStmt=$oDB->prepare("select name, age from users where userid=:userid");
$hStmt->execute(array(':userid',$nUserID));
This code is not vulnerable to SQL injection because it correctly uses parameterized queries. By utilizing the PHP PDO module and binding variables to the prepared statements, SQL injection can easily be prevented.

Vulnerable Usage







// Example #1 (using old mysql library)
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
This code is vulnerable to a SQL injection attack as it uses an outdated mysql library, which does not support prepared statements. This vulnerability can be avoided by validation of the user’s input.



// Example #2 (incorrectly preparing a statement with PDO)
$oDB=new PDO('... your connection details...');
$hStmt=$oDB->prepare("select name, age from users where userid=".$_GET['userid']);
$hStmt->execute();
Previous
Next Post »