[英]PHP PDO / Retrieving OUT Parameters from MySQL Stored Procedure
我需要從MySQL存儲過程中檢索OUT參數。 我找不到任何能解釋這一點(對我來說很有意義)的東西。
try {
$dsn = 'mysql:dbname=db_name;host=localhost';
$dbh = new PDO($dsn, 'usr_name', 'password');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$stmt = $dbh->prepare("CALL db.stprNewUser(:usrEmail,:newUserOK,:stprComment)");
$stmt->bindParam(':usrEmail', $tmpEmail, PDO::PARAM_STR);
$stmt->bindParam(':newUserOK', $newUserOK, PDO::PARAM_INT,1);
$stmt->bindParam(':stprComment', $stprComment, PDO::PARAM_STR,100);
$stmt->execute();
$outputArray = $dbh->query("select @newUserOK, @stprComment")->fetch(PDO::FETCH_ASSOC);
print "procedure returned [" . $outputArray['@newUserOK'] . $outputArray['@stprComment'] . "]\n";
我在另一個SO項目上找到了最后兩行,但它只返回NULL值。
試試這個...看看是否可行...
try
{
$dsn = 'mysql:dbname=db_name;host=localhost';
$dbh = new PDO($dsn, 'usr_name', 'password');
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
//$stmt = $dbh->prepare("CALL db.stprNewUser(:usrEmail,:newUserOK,:stprComment)");
//changed :newUserOK to @newUserOK
//changed :stprComment to @stprComment
$stmt = $dbh->prepare("CALL db.stprNewUser(:usrEmail,@newUserOK,@stprComment);");
//declare only input parameters.
//good pratice put string length. assuming varchar(100).
$stmt->bindParam(':usrEmail', $tmpEmail, PDO::PARAM_STR,100);
//dont need these
// $stmt->bindParam(':newUserOK', $newUserOK, PDO::PARAM_INT,1);
// $stmt->bindParam(':stprComment', $stprComment, PDO::PARAM_STR,100);
$stmt->execute();
$outputArray = $dbh->query("select @newUserOK, @stprComment;")->fetchAll();
foreach($outputArray as $row)
{
"NewUserOk:" . $row["@newUserOk"] . ", StprComment:" . $row["@stprComment"];
}
//$outputArray = $dbh->query("select @newUserOK, @stprComment")->fetch(PDO::FETCH_ASSOC);
//print "procedure returned [" . $outputArray['@newUserOK'] . $outputArray['@stprComment'] . "]\n";
除了使用MySQL會話變量外,您還可以使用bindParam() :
bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
將PHP變量綁定到用於准備語句的SQL語句中相應的命名或問號占位符。 與PDOStatement :: bindValue()不同,該變量綁定為引用,並且僅在調用PDOStatement :: execute()時進行評估。
大多數參數是輸入參數,即,以只讀方式用於構建查詢的參數。 一些驅動程序支持存儲過程的調用,這些存儲過程將數據作為輸出參數返回,而某些驅動程序還作為輸入/輸出參數,它們既發送數據又進行更新以接收數據。
不要忘記使用相應的占位符:
$stmt = $dbh->prepare("CALL superior_main_db.stprNewUser(:usrEmail, :newUserOK, :stprComment)");
執行該語句后,變量將自動包含所需的值。
要檢索@newUserOK和@stprComment變量,只需在調用存儲過程后執行以下查詢,如下所示
SELECT @newUserOK, @stprComment
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.