Skip to content
Advertisement

How to debug PDO database queries?

Before moving to PDO, I created SQL queries in PHP by concatenating strings. If I got database syntax error, I could just echo the final SQL query string, try it myself on the database, and tweak it until I fixed the error, then put that back into the code.

Prepared PDO statements are faster and better and safer, but one thing bothers me: I never see the final query as it’s sent to the database. When I get errors about the syntax in my Apache log or my custom log file (I log errors inside a catch block), I can’t see the query that caused them.

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

Advertisement

Answer

Looking in the database log

Although Pascal MARTIN is correct that PDO doesn’t send the complete query to the database all at once, ryeguy‘s suggestion to use the DB’s logging function actually allowed me to see the complete query as assembled and executed by the database.

Here’s how:
(These instructions are for MySQL on a Windows machine – your mileage may vary)

  • In my.ini, under the [mysqld] section, add a log command, like log="C:Program FilesMySQLMySQL Server 5.1datamysql.log"
  • Restart MySQL.
  • It will start logging every query in that file.

That file will grow quickly, so be sure to delete it and turn off logging when you’re done testing.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement