Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve (or simulate) full query from PDO prepared statement

I stumbled upon this question from two years ago.

Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.

The winning answer states that

[...] You can also get what you want if you set the PDO attribute PDO::ATTR_EMULATE_PREPARES. In this mode, PDO interpolate parameters into the SQL query and sends the whole query when you execute().

But it doesn't mention how to get the resulting query string. I know it's a bad idea performance wise but that doesn't bother me in debug mode. Does anybody know how to do this?

PS If there is some way I could have reopened / drawn attention to the original two year old topic instead of opening a new one, please let me know.

like image 512
Michael Clerx Avatar asked Sep 20 '10 18:09

Michael Clerx


People also ask

Which method is used to execute prepared query in PDO?

To prepare and execute a single SQL statement that accepts no input parameters, use the PDO::exec or PDO::query method. Use the PDO::exec method to execute a statement that returns no result set.

What method of the PDO Command object is typically used to retrieve a list of results from a database query?

To fetch results in PDO, you have the option of $stmt->fetch() or $stmt->fetchAll() . The former is more versatile, as it can be used to fetch one row, or all if used in a loop. The latter is basically syntactic sugar, as it lets fetch your entire result set in an array with that one command.

Does PDO use prepared statements?

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.


1 Answers

I believe this is mentioned in the original question that was reference in this one. However there is actually supposed to be a method for retrieving this data.

PDOStatement::debugDumpParams

However it isn't currently working as documented. There is a bug report and patch submitted for it here http://bugs.php.net/bug.php?id=52384 in case anyone is interested in voting on it. Until it's fixed it seems like you are left to use query logging or setting a custom statement class using the PDO::ATTR_STATEMENT_CLASS attribute.

like image 103
Chris Gutierrez Avatar answered Sep 19 '22 19:09

Chris Gutierrez