8

我在 MySQL 数据库中有一个简单的存储过程:

DELIMITER $$
CREATE DEFINER=`vidhu`@`%` PROCEDURE `test`(var_datain TEXT)
BEGIN
    SELECT var_datain;
END

在 mysql-workbench 中调用此过程时,它会返回我输入的数据:

截图表单mysql工作台

现在,当我使用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];
4

3 回答 3

24

您需要使用bindValue而不是bindParam

当您使用 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
于 2012-08-07T00:52:14.237 回答
-1

bindParam函数只接受值变量,这就是为什么参数二hai不是变量的原因cannot be passed。所以不需要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];

这应该解决您的问题,而不是上面的答案。

于 2020-12-22T06:32:57.733 回答
-6

以下代码适用于没有准备语句的调用!

$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;
于 2015-01-22T20:11:09.157 回答