Are PDO prepared statements sufficient to prevent SQL injection?

Technology CommunityCategory: PHPAre PDO prepared statements sufficient to prevent SQL injection?
VietMX Staff asked 3 years ago
Problem

Let’s say I have code like this:

$dbh = new PDO("blahblah");

$stmt = $dbh->prepare('SELECT * FROM users where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );

Is that truly all I need to do to avoid SQL injections? Is it really that easy?

The short answer is NO, PDO prepares will not defend you from all possible SQL-Injection attacks. For certain obscure edge-cases for example:

$pdo->query('SET NAMES gbk');
$var = "\xbf\x27 OR 1=1 /*";
$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';
$stmt = $pdo->prepare($query);
$stmt->execute(array($var));

The rendered query will be that will return more than 1 row:

SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1