問題描述
在轉向 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 的建議實際上允許使用 DB 的日志記錄功能我可以看到由數據庫組裝和執行的完整查詢.
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 FilesMySQLMySQL Server 5.1datamysql.log"
- 重啟 MySQL.
- 它將開始記錄該文件中的每個查詢.
- In
my.ini
, under the[mysqld]
section, add alog
command, likelog="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.
這篇關于如何調試 PDO 數據庫查詢?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!