在PHP 中使用PDO 檢索MySQL 預存程序變數
從MySQL 儲存過程中擷取LAST_INSERT_ID() 的值可能是一項艱鉅的值可能是一項艱鉅的值可能是一項艱鉅的值可能是一項艱鉅的值可能是一項艱鉅的值可能是一項艱鉅的值可能是一項艱鉅的值可能是一項艱鉅的值任務。儘管網路上有充足的文檔,但這個過程對許多開發人員來說往往難以捉摸。本文旨在揭開這個問題的神秘面紗,提供使用 PHP PDO 檢索變數值的逐步指南。
帶有「IN」、「INOUT」和「OUT」的 PHP 過程參數參數
檢索變數的關鍵是理解所涉及的兩階段過程。首先,必須使用必要的輸入參數和儲存結果的變數來執行該過程。隨後,執行單獨的查詢以檢索指定變數中的值。
使用PDO 檢索MySQL 預存程序的兩階段過程
為了演示此過程,讓我們考慮以下場景:
SQL 流程:
CREATE PROCEDURE `demoSpInOutSqlVars`(IN pInput_Param INT, INOUT pInOut_Param INT, OUT pOut_Param INT) BEGIN /* * Pass the full names of SQL User Variable for these parameters. e.g. '@varInOutParam' * These 'SQL user variables names' are the variables that Mysql will use for: * 1) finding values * 2) storing results * * It is similar to 'variable variables' in PHP. */ SET pInOut_Param := ABS(pInput_Param) + ABS(pInOut_Param); /* always positive sum */ SET pOut_Param := ABS(pInput_Param) * -3; /* always negative * 3 */ END
PHP程式碼:
// DB Connection $db = appDIC('getDbConnection', 'default'); // get the default db connection $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // Set PHP Variables $phpInParam = 5; $phpInOutParam = 404; // PHP InOut variable $phpOutParam = null; // PHP Out variable // Define and Prepare the SQL procedure call $sql = "call demoSpInOut(:phpInParam, @varInOutParam, /* mysql variable name will be read and updated */ @varOutParam)"; /* mysql variable name that will be written to */ $stmt = $db->prepare($sql); // Bind PHP Variables and Set SQL Variables $stmt->bindParam(':phpInParam', $phpInParam, PDO::PARAM_INT); $db->exec("SET @varInOutParam = $phpInOutParam"); // This is safe as it just sets the value into the MySql variable. // Execute the procedure $allOk = $stmt->execute(); // Get the SQL Variables into the PHP variables $sql = "SELECT @varInOutParam AS phpInOutParam, @varOutParam AS phpOutParam FROM dual"; $results = current($db->query($sql)->fetchAll()); $phpInOutParam = $results['phpInOutParam']; $phpOutParam = $results['phpOutParam']; // Display the PHP variables echo "phpInParam = " . $phpInParam . "\n"; echo "phpInOutParam = " . $phpInOutParam . "\n"; echo "phpOutParam = " . $phpOutParam . "\n";
附加說明:
結論:
在PHP PDO 中檢索MySQL 預存程序變數是一個多方面的過程,涉及執行過程並從SQL 使用者變數中檢索值。透過遵循上述步驟,開發人員可以使用 PDO 有效地從 MySQL 預存程序存取所需的變數。
以上是如何在 PHP 中使用 PDO 檢索 MySQL 預存程序變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!