How to debug PDO database queries?

You say this :

I never see the final query as it’s
sent to the database

Well, actually, when using prepared statements, there is no such thing as a “final query :

  • First, a statement is sent to the DB, and prepared there
    • The database parses the query, and builds an internal representation of it
  • And, when you bind variables and execute the statement, only the variables are sent to the database
    • And the database “injects” the values into its internal representation of the statement

So, to answer your question :

Is there a way capture the complete
SQL query sent by PDO to the database
and log it to a file?

No : as there is no “complete SQL query” anywhere, there is no way to capture it.

The best thing you can do, for debugging purposes, is “re-construct” an “real” SQL query, by injecting the values into the SQL string of the statement.

What I usually do, in this kind of situations, is :

  • echo the SQL code that corresponds to the statement, with placeholders
  • and use var_dump (or an equivalent) just after, to display the values of the parameters
  • This is generally enough to see a possible error, even if you don’t have any “real” query that you can execute.

This is not great, when it comes to debugging — but that’s the price of prepared statements and the advantages they bring.

Leave a Comment