PDO 的查询与执行

PDO#39;s query vs execute(PDO 的查询与执行)
本文介绍了PDO 的查询与执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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 运行标准的 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

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

Best practice is to stick with prepared statements and execute for increased security.

另见:PDO 准备好的语句是否足以防止 SQL注射?

这篇关于PDO 的查询与执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)