php - PDO 的查询与执行

标签 php pdo

他们都做同样的事情,只是不同吗?

除了使用prepare之间有什么区别

$sth = $db->query("SELECT * FROM table");
$result = $sth->fetchAll();

$sth = $db->prepare("SELECT * FROM table");
$sth->execute();
$result = $sth->fetchAll();

?

最佳答案

query运行没有参数化数据的标准 SQL 语句。

execute运行一个准备好的语句,它允许您绑定(bind)参数以避免需要转义或引用参数。如果您多次重复查询,execute 也会执行得更好。准备好的语句示例:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

最佳做法是坚持使用准备好的语句并执行以提高安全性

另请参阅:Are PDO prepared statements sufficient to prevent SQL injection?

关于php - PDO 的查询与执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4700623/

相关文章:

php - 在 SQL 查询、PHP 中添加变量和常量的简短语法

php - 无法使用 PHP PDO 准备更新 MySQL 中的数据

php - 重复 key 更新后插入进程

PHP + PDO 在多列搜索时分页

PHP PDO : Syntax error or access violation

javascript - 使用 oracle 查询创建图表

PHP 解析/语法错误;以及如何解决它们

PHP Lame 流过滤器

php - 在数据库中查找、获取和替换部分字符串的最快方法

php - PDO + MsSQL + freetds = INSERT 查询中的错误字符