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/57904456/

相关文章:

php - php-PDO 中的 SQL 命令不起作用 - 不会引发错误

php - 可捕获的 fatal error : Object of class PDOStatement could not be converted to string

php - 如何使用 Angular 显示 PHP MySQL 查询的输出

php - 使用 php 进行 http 到 https 转发

php - Jquery 表单验证并通过 PHP 脚本使用 Mysql 数据库检查值

php - 第二次查看页面时如何更改代码

php - 表名和字段名是变量的 PDO 语句

php - (整数)假;在PHP中为什么会这样?

php - 检查用户凭据 PHP MySQL

php - PDO - 准备好的语句不能正确处理变量