问题描述
他们俩都做相同的事情,只是做的不同吗?
Are they both do the same thing, only differently?
除了使用prepare
之间还有其他区别
Is there any difference besides using prepare
between
$sth = $db->query("SELECT * FROM table");
$result = $sth->fetchAll();
和
$sth = $db->prepare("SELECT * FROM table");
$sth->execute();
$result = $sth->fetchAll();
?
推荐答案
query
运行标准SQL语句,并要求您正确转义所有数据,以避免SQL注入和其他问题.
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
运行一条准备好的语句,该语句使您可以将参数绑定到避免需要转义或引用参数.如果您多次重复查询,execute
的性能也会更好.准备好的语句示例:
execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute
will also perform better if you are repeating a query multiple times. Example of prepared statements:
$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
最佳实践是坚持使用准备好的语句,并使用execute
来提高安全性.
Best practice is to stick with prepared statements and execute
for increased security.
另请参见: PDO准备好的语句是否足以防止SQL注射?
这篇关于PDO的查询与执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!