一千萬個為什麽

搜索

如何查看調用查詢的最終文本到mysqli-> prepare?

像這樣的代碼後:

$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);

如何查看執行的實際SQL語句?

(它應該看起來像“從城市選擇區域名稱='西米谷';”)

我已經意識到,在這種簡單的情況下,簡單地重構查詢將非常容易......但是我如何以一般方式訪問它,這將適用於非常復雜的預處理語句,以及我不一定已經理解的情況查詢的預期結構等。是否有一些函數或方法可以在語句對象上調用,它將在綁定後返回SQL查詢的實際文本?

最佳答案

當您使用預準備語句時,沒有“ SQL查詢”:

  • First, you have a statement, that contains placeholders
    • This statement is sent to the DB server, and prepared there
    • which means that the SQL statement is analysed, parsed, and that some data-structure representing it is prepared in memory
  • And, then, you have bound variables
    • which are sent to the server
    • and the prepared statement is executed -- working on those data

但是實際上沒有重構真正的實際SQL查詢 - 既不在PHP方面,也不在數據庫方面。

因此,沒有辦法獲得準備好的語句的SQL - 因為沒有這樣的SQL


If you need to see some informations, for debugging purposes, as your said, you'll generally have two kind of options :

  • Either create the SQL query that would correspond to the prepared statement + binding by hand.
  • Or ouput the code of the statement, with the placeholders ; and the list of data
    • This means you will not have a real SQL query that can be executed
    • But it'll generally be enough, to help with debugging

轉載註明原文: 如何查看調用查詢的最終文本到mysqli-> prepare?