如何调试PDO数据库查询? [英] How to debug PDO database queries?

查看:66
本文介绍了如何调试PDO数据库查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在转向PDO之前,我通过连接字符串在PHP中创建了SQL查询.如果遇到数据库语法错误,我可以回显最终的SQL查询字符串,然后在数据库中自己尝试,然后对其进行调整,直到修复错误,然后将其重新放入代码中.

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.

准备好的PDO语句更快,更好,更安全,但是有一件事困扰着我:在将最终查询发送到数据库时,我再也看不到它.当我在Apache日志或自定义日志文件中收到有关语法的错误时(我在catch块中记录了错误),我看不到导致它们的查询.

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.

是否可以捕获由PDO发送到数据库的完整SQL查询并将其记录到文件中?

推荐答案

在数据库日志中查找

尽管 Pascal MARTIN 是正确的,即PDO不会一次将完整查询发送到数据库,但 ryeguy 建议使用数据库的日志记录功能实际上是允许的我看到了由数据库组装并执行的完整查询.

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.

方法如下: (这些说明适用于Windows计算机上的MySQL,您的里程可能会有所不同

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

  • my.ini[mysqld]部分下,添加log命令,例如log="C:\Program Files\MySQL\MySQL Server 5.1\data\mysql.log"
  • 重新启动MySQL.
  • 它将开始记录该文件中的每个查询.
  • In my.ini, under the [mysqld] section, add a log command, like log="C:\Program Files\MySQL\MySQL Server 5.1\data\mysql.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.

这篇关于如何调试PDO数据库查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆