Starting to stop SQL-injections

In a lot of PHP-examples strings are concatenated before a database query is being executed as below. Some examples advise to use PHP-functions mysql_real_escape_string() and/or addslashes() to make database query safe against SQL-injections. But this isn’t really a solution as when using addslashes() also requires the use of stripslashes() after retrieving data from a database. Some sites show the lack of a proper implementation and show the famous \’ string in a website.

$sth = $dbh_rw->prepare('select userid from accounts where username = "'.$form_username.'"');
$sth->execute();

Like in Perl with DBI, also PHP has PDO that allows for variables to be parameterised while executing a query as in the example below. This removes the need for home made solutions that don’t cover all usecases and allows for a way to provide a stable and more secure interface for your applications when communicating with databases.

$sth = $dbh_rw->prepare('select userid from accounts where username = ?');
$sth->execute(array($form_username));

This doesn’t stop the need of sanitizing variables like as with input from users.