問題描述
我在 MySQL 數據庫中有一個簡單的存儲過程:
I have a simple stored procedure in MySQL database:
DELIMITER $$
CREATE DEFINER=`vidhu`@`%` PROCEDURE `test`(var_datain TEXT)
BEGIN
SELECT var_datain;
END
在 mysql-workbench 中調用此過程時,它返回我輸入的數據:
When calling this procedure in mysql-workbench it returns the data I put in:
現在,當我使用 pdo 從 PHP 調用它時,出現錯誤:
Now when I call it from PHP using pdo I get an error:
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];
推薦答案
您需要使用 bindValue 而不是 bindParam.
You need to use bindValue instead of bindParam.
當你使用 bindParam 時,它綁定的是提供給參數的變量,而不是變量的值.
When you use bindParam, it binds the variable provided to the parameter, not the value of the variable.
所以,如果你這樣做:
$x = 5;
$stmt->bindParam(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 6 instead of 5
它實際上是用 6 而不是 5 來執行的.為此,該方法必須具有對變量的引用.你不能引用文字,所以這意味著 bindParam 不能與文字(或任何你不能引用的東西)一起使用.
It's actually executed with 6 rather than 5. To do this, the method must have a reference to the variable. You cannot have a reference to a literal, so this means that bindParam cannot be used with literals (or anything you can't have a reference to).
$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
這篇關于在帶有存儲過程的 php 中使用 pdo的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!