問題:
如何擷取LAST_INSINSERT() 值使用PH🎜>如何擷取LAST_INSINSERT() 值使用PH和PDO 來自MySQL 預存程序?
過程:
考慮以下PHP 代碼:
<?php $stmt = $db->prepare("CALL simpleProcedure(:name,:returnid)"); $stmt->bindValue(':name', $name, PDO::PARAM_STR); $stmt->bindParam(':returnid', $returnid, PDO::PARAM_INT, 11); $stmt->execute(); echo $returnid; ?>
雖然此代碼可能看起來正確,由於PDO 中長期存在的錯誤,它不起作用。
解決方案:
要從MySQL 流程擷取輸出,請依照下列步驟操作:
第1 步驟:執行過程
使用您的輸入運行過程並指定哪些MySQL 變數將儲存結果。例如:
<?php $stmt = $db->prepare("CALL simpleProcedure(:name, @returnid)"); $stmt->bindValue(':name', $name, PDO::PARAM_STR); $stmt->execute(); ?>
步驟2:查詢MySQL 變數
執行單獨的查詢選擇MySQL 變數:
<?php $stmt = $db->query("SELECT @returnid"); $result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0); $returnid = $result[0]; ?>
範例:
以下程式碼包含更詳細的範例,顯示不同參數類型(IN、INOUT、OUT)使用變數: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); SET pOut_Param := ABS(pInput_Param) * -3; END$$
PHP 程式碼:
<?php // Bind PHP variables $phpInParam = 5; $phpInOutParam = 404; $phpOutParam = null; // Prepare the SQL procedure call $sql = "call demoSpInOut(:phpInParam, @varInOutParam, @varOutParam)"; $stmt = $db->prepare($sql); $stmt->bindParam(':phpInParam', $phpInParam, PDO::PARAM_INT); // Set the SQL User INOUT variables $db->exec("SET @varInOutParam = $phpInOutParam"); // Execute the procedure $stmt->execute(); // Get the SQL variables into PHP variables $sql = "SELECT @varInOutParam AS phpInOutParam, @varOutParam AS phpOutParam FROM dual"; $results = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC); $phpInOutParam = $results[0]['phpInOutParam']; $phpOutParam = $results[0]['phpOutParam']; // Display the PHP variables echo "phpInParam: $phpInParam<br>"; echo "phpInOutParam: $phpInOutParam<br>"; echo "phpOutParam: $phpOutParam<br>"; ?>依照下列步驟,您可以使用PDO 有效地擷取MySQL 預存程序的輸出。
以上是如何在 PHP 中使用 PDO 從 MySQL 預存程序檢索輸出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!