SQL Injection Bug
Thursday, November 2nd, 2006More often than not many developers tend to overlook the SQL Injection bug pointed out by Joel. Here is the problem:
$x = pg_query("select * from accounts where name='" . $_GET["name"] . "'");
If the name contains words like ‘doesn’t’ the singe quote in the middle messes up the query. This can be mitigated by two ways.
1) Using Magic Quotes - which will escape the incoming strings but they were an annoyance and therefore they removed it from PHP 6.
2) Using mysql_real_escape_string as follows:
$name = “‘” . mysql_real_escape_string($_GET["name"] ) . “‘”;
Of course you need to validate that it is not numeric before you can pass the string to the mysql_real_escape_string.
You can find a good example in the PHP net .