[英]Using pdo in php with stored procedure
我在 MySQL 數據庫中有一個簡單的存儲過程:
DELIMITER $$
CREATE DEFINER=`vidhu`@`%` PROCEDURE `test`(var_datain TEXT)
BEGIN
SELECT var_datain;
END
在 mysql-workbench 中調用此過程時,它會返回我輸入的數據:
現在,當我使用pdo從 PHP 調用它時,出現錯誤:
Fatal error: Cannot pass parameter 2 by reference in C:/apache......(3rd line)
這是我的PHP代碼:
$db = new PDO(DSN, DBUSER, DBPASS);
$stmt = $db->prepare("CALL test(?)");
$stmt->bindParam(1, 'hai!', PDO::PARAM_STR);
$rs = $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $result[0];
當您使用 bindParam 時,它將提供給參數的變量綁定,而不是變量的值。
所以,如果你這樣做:
$x = 5;
$stmt->bindParam(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 6 instead of 5
它實際上是用 6 而不是 5 執行的。為此,該方法必須具有對變量的引用。 您不能引用文字,因此這意味着 bindParam 不能與文字(或您無法引用的任何內容)一起使用。
$x = 5;
$stmt->bindValue(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 5 instead of 6
然后:
$stmt->bindParam(1, 1, PDO::PARAM_INT);
//invalid because there's no way to pass a literal 1 by reference
$stmt->bindValue(1, 1, PDO::PARAM_INT);
//valid
bindParam
函數只接受值變量,這就是為什么cannot be passed
不是變量的參數二hai
。 所以不需要bindValue,而是正確使用bindParam。 示例:使用 bindParam 時:來自您的代碼段。
$a = "hai";
$db = new PDO(DSN, DBUSER, DBPASS);
$stmt = $db->prepare("CALL test(?)");
$stmt->bindParam(s, $a, PDO::PARAM_STR);
$rs = $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $result[0];
這應該可以解決您的問題,而不是上面的答案。
以下代碼適用於不使用 prepare 語句的調用!
$query="CALL store_procedure_name(@a)";
$conn->query($query);
$query="SELECT @a as outvar;";
$result = $conn->query($query);
foreach ($result as $x)
{
$res=$x['outvar'];
}
echo $res;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.