简体   繁体   English

我什么时候使用PDO :: query?

[英]When do I use PDO::query?

Much have been written about the benefits of using PDO::prepare , but little has been written on the benefits of using PDO::query . 关于使用PDO::prepare的好处已经写了很多,但很少有关于使用PDO::query的好处。 I believe PDO::query is created to serve a purpose and there ought to be some relative advantage of using this function over PDO::prepare . 我相信PDO::query是为了达到目的而创建的,并且在PDO::prepare上使用这个函数应该有一些相对优势。

I have a query that goes like this: 我有一个像这样的查询:

SELECT * from Table ORDER BY id DESC LIMIT 100;

This query contains no user input for escaping and no variables for repeated querying. 此查询不包含用于转义的用户输入,也不包含用于重复查询的变量。 Should I use PDO::query , go back to mysqli_query or stick to PDO::prepare in this case? 我应该使用PDO::query ,在这种情况下,回到mysqli_query还是坚持PDO::prepare

UPDATE : Further examination on the general query log shows this for both PDO::prepare and PDO::query : 更新 :对通用查询日志的进一步检查显示PDO::preparePDO::query

22 Connect user@localhost on Database
22 Prepare SELECT * from Table ORDER BY id DESC LIMIT 100
22 Execute SELECT * from Table ORDER BY id DESC LIMIT 100
22 Close stmt   
22 Quit

I was expecting PDO::query to produce: 我期待PDO::query产生:

22 Connect user@localhost on Database
22 Query SELECT * from Table ORDER BY id DESC LIMIT 100
22 Quit

But this only happens, and to both, when setAttribute(PDO::ATTR_EMULATE_PREPARES, true) . 但是这只发生在两者之间,当setAttribute(PDO::ATTR_EMULATE_PREPARES, true) I am quite surprised at the result that I am getting. 我对得到的结果感到非常惊讶。 It seems that PDO::query generates prepared statements as well. 似乎PDO::query生成PDO::query准备语句。

If you just need it once, then there's no point in creating a prepared statement (which unless emulated would result in two network transmissions to the database). 如果您只需要一次,那么创建预准备语句就没有意义(除非模拟将导致两次网络传输到数据库)。 Much less so when there are no variable parameters to be bound. 当没有可变参数被约束时,更不用说了。

PDO::query is not about benefits. PDO::query不是关于好处。 Its use comes with the absence of any. 它的使用伴随着没有任何。 One-off queries don't benefit from the potential speed advantage of prepared statements. 一次性查询不会从预准备语句的潜在速度优势中受益。

I guess I have missed it completely. 我想我完全错过了它。 It states in the PHP manual for PDO::query that: 它在PHP手册中指出PDO::query

PDOStatement PDO::query ( string $statement )

Parameters 参数

statement 声明

The SQL statement to prepare and execute. 准备和执行的SQL语句。

What this means is that the SQL statement is prepared even with PDO::query . 这意味着即使使用PDO::query 可以准备SQL语句。 Therefore there is absolutely no advantage to use PDO::query except saving a line or two on the PHP script. 因此,除了在PHP脚本上保存一行或两行之外,使用PDO::query绝对没有优势。 This is verified by the general query log shown in the question above. 这可以通过上面问题中显示的常规查询日志进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM