Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to escape DB input?

I read that with PDO you don't need to escape variables if you use prepare and pass the variables in execute:

$st = $dbh->prepare("INSERT INTO mytable (name,email) VALUES (?,?)");
$st->execute(array($_POST['name'], $_POST['email']));

Is this tru?

Or do I still need to do something with $_POST there?

like image 641
JohnSmith Avatar asked Dec 05 '11 14:12

JohnSmith


1 Answers

On prepared statements, no escaping is necessary (and escaping things yourself will result in double-escaping, causing escaped data to be written to the DB).

However, PDO prepared statements CANNOT handle all query variants, and sometimes you'll have to insert "foreign" data directly into a query string, which means you'll be responsible for escaping it properly. In particular, dynamic queries where the table and/or field names change cannot be specified using prepared statements. e.g.

SELECT ? FROM ? WHERE ?=?

cannot be done. Only values can specified with placeholders.

like image 108
Marc B Avatar answered Sep 21 '22 01:09

Marc B