他们都做同样的事情,只是不同吗?
除了使用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/