問題描述
他們都做同樣的事情,只是不同嗎?
Are they both do the same thing, only differently?
$sth = $db->query("SELECT * FROM table");
$result = $sth->fetchAll();
和
$sth = $db->prepare("SELECT * FROM table");
$sth->execute();
$result = $sth->fetchAll();
?
推薦答案
query
運(yùn)行標(biāo)準(zhǔn)的 SQL 語句并要求您正確轉(zhuǎn)義所有數(shù)據(jù)以避免 SQL 注入和其他問題.
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
運(yùn)行準(zhǔn)備好的語句,它允許您綁定參數(shù)以避免需要轉(zhuǎn)義或引用參數(shù).如果您多次重復(fù)查詢,execute
也會(huì)表現(xiàn)得更好.準(zhǔn)備好的語句示例:
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
最佳做法是堅(jiān)持使用準(zhǔn)備好的語句并執(zhí)行
以提高安全性.
Best practice is to stick with prepared statements and execute
for increased security.
另見:PDO 準(zhǔn)備好的語句是否足以防止 SQL注射?
這篇關(guān)于PDO 的查詢與執(zhí)行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!