Question Overflow
Question Overflow

Reputation: 11275

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. 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.

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?

UPDATE: Further examination on the general query log shows this for both PDO::prepare and PDO::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:

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). I am quite surprised at the result that I am getting. It seems that PDO::query generates prepared statements as well.

Upvotes: 3

Views: 258

Answers (2)

Question Overflow
Question Overflow

Reputation: 11275

I guess I have missed it completely. It states in the PHP manual for PDO::query that:

PDOStatement PDO::query ( string $statement )

Parameters

statement

The SQL statement to prepare and execute.

What this means is that the SQL statement is prepared even with PDO::query. Therefore there is absolutely no advantage to use PDO::query except saving a line or two on the PHP script. This is verified by the general query log shown in the question above.

Upvotes: 2

mario
mario

Reputation: 145482

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. Its use comes with the absence of any. One-off queries don't benefit from the potential speed advantage of prepared statements.

Upvotes: 2

Related Questions