開發中常遇到 PHP 呼叫 MySQL 預存程序,透過 OUT 參數獲取返回值時,不同 Session 取得的結果不一致(有值 vs NULL)。本文透過實測複現並給出解決方案。
預存程序 usp_s2 執行兩次 SELECT:第一次查詢資料,第二次將統計結果存入 OUT 參數 @a。
Session 1 呼叫後 SELECT @a 正常得到 4430。
Session 2 直接 SELECT @a 得到 NULL。
原因在於:PHP 每次請求通常建立新連線(新 Session),OUT 參數屬於 Session 級變數,跨 Session 不共享。
mysqli::multi_query 在同一連線內完成呼叫與取值<?php
$hostname = "127.0.0.1";
$username = "wubx";
$password = "wubxwubx";
$database = "proxydb";
$db = new mysqli($hostname, $username, $password, $database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// 同一個 multi_query 執行呼叫與讀取 OUT 參數
$result = $db->multi_query("CALL usp_s2(@total); SELECT @total;");
if ($result) {
do {
if ($r = $db->store_result()) {
if ($r->field_count == 2) {
while ($row = $r->fetch_row()) {
print "ip: $row[0], port: $row[1]\n";
}
} else {
$row = $r->fetch_row();
print "total: $row[0]\n";
}
}
} while ($db->next_result());
}
$db->close();
?>
輸出結果正常顯示資料與總計 4430,解決跨 Session 導致的返回值不一致問題。