How do I sanitize input with PDO?

If you use PDO you can parametize your queries, removing the need to escape any included variables.

See here for a great introductory tutorial for PDO.

Using PDO you can seperate the SQL and passed parameters using prepared statements, this removes the need to escape strings, as because the two are held seperately then combined at execution, the parameters are automatically handled as stings, from the above source:

   // where $dbh is your PDO connection

   $stmt = $dbh->prepare("SELECT * FROM animals WHERE animal_id = :animal_id AND animal_name = :animal_name");

   /*** bind the paramaters ***/
   $stmt->bindParam(':animal_id', $animal_id, PDO::PARAM_INT);
   $stmt->bindParam(':animal_name', $animal_name, PDO::PARAM_STR, 5);

   /*** execute the prepared statement ***/
   $stmt->execute();

Note: sanitization occurs during variable binding ($stmt->bindParam)

Other resources:

http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

http://www.phpeveryday.com/articles/PDO-Prepared-Statement-P550.html

http://php.net/manual/en/pdo.prepared-statements.php

Leave a Comment