問題描述
可能的重復:
從 PDO 準備好的語句中檢索(或模擬)完整查詢
我不明白為什么我的查詢返回 0 行..它實現了一些非常動態的搜索功能,以及很多 if/loop 語句等.因此要調試它,我想看看到底是什么字符串正在發送到服務器.有沒有辦法通過 PHP 做到這一點?
I can't figure out why my query is returning 0 rows.. it implements some very dynamic search functionality, and a lot of if/loop statements etc. Therefor to debug it, I'd like to see EXACTLY what string is being sent to the server. Is there a way to do this through PHP?
有沒有辦法詢問服務器上次查詢是什么",或者告訴 PDO告訴我你發送了什么"?
Is there maybe a way to ask the server "what was the last query", or tell PDO "show me what you sent"?
我看到一個使用 str_replace
手動輸入值代替 :fieldValue
的響應,但這可能是語法問題(或者它可能正在經歷不正確的循環,等),此方法無濟于事.
I saw one response using str_replace
to manually enter the values in place of :fieldValue
, but it's likely a syntax problem (or maybe it's going through an incorrect loop, etc), which this method doesn't help with.
使用 bindValue(":fieldValue", $value);
如果這有所不同.
Using bindValue(":fieldValue", $value);
if that makes a difference.
編輯
結果是一個簡單的 if ($var="true") { ...
應該是 if ($var=="true") { ...代碼>.從這個意義上說,我猜 PHP 與 Java 不一樣?無論哪種方式,問題仍然存在(因為我經常遇到這種情況).我不得不使用一系列
echo "You are Here";
來找到這個錯誤,因為它在技術上有效但不正確.如果我有最后的 SQL 語句,我可以看到哦,我的代碼添加了 where column = true
,一定是通過了錯誤的 IF...".
Turns out it was a simple if ($var="true") { ...
which should have been if ($var=="true") { ...
. PHP I guess is not the same as Java in that sense? Either way, the question still stands (as I run into this often). I had to use a series of echo "You are Here";
to find this error, as it was technically valid but not correct. If I had the final SQL statement, I could have seen "Oh, my code has added the where column = true
, must have gone through the wrong IF...".
推薦答案
這是關于 SQL 調試的一個最常見的誤區.我需要在準備后查看查詢才能判斷是否發生了錯誤".事實是,你不,我會告訴你原因.
That's the single most common myth about SQL debugging. "I need to see the query after preparation to be able to tell if an error occurred". The fact is, you don't, and I'll tell you why.
準備好查詢后,可以將占位符視為有效字符串/整數.你不在乎里面有什么.
Once a query has been prepared, the placeholder can be considered as a valid string/integer. You don't care what's in it.
此外,如果您正確設置了 PDO,您將獲得詳細的 PDOException
詳細說明您遇到的錯誤以及錯誤發生位置的完整回溯,以及您獲得錯誤字符串來自 MySQL,這使得語法錯誤很容易被發現.
Also, if you set up PDO correctly, you'll get a detailed PDOException
detailing the error you've had along with a complete backtrace of where the error happened, plus you get the error string from MySQL, which makes syntax errors very easy to find.
要啟用 PDO 異常并禁用模擬準備:
To enable PDO Exceptions and disable emulated prepares:
$pdo = new PDO("mysql:host=localhost;dbname=database_name", "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
這篇關于PDO 調試 - 綁定后查看查詢?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!