如何使用 PDO 清理输入?

2021-12-26 00:00:00 php pdo

当我使用 PDO 库?

如何使用 PDO 正确转义用户输入?

How do I properly escape user input with PDO?

推荐答案

如果您使用 PDO,您可以参数化您的查询,无需转义任何包含的变量.

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

请参阅此处,了解 PDO 的精彩介绍教程.

See here for a great introductory tutorial for PDO.

使用 PDO,您可以使用准备好的语句将 SQL 和传递的参数分开,这消除了对字符串进行转义的需要,因为这两者是分开保存的,然后在执行时组合,参数会自动作为字符串处理,来自上述来源:

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();

注意:在变量绑定期间进行清理 ($stmt->bindParam)

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

其他资源:

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-声明.php

相关文章