在带有存储过程的 php 中使用 pdo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11837849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using pdo in php with stored procedure
提问by Krimson
I have a simple stored procedure in MySQL database:
我在 MySQL 数据库中有一个简单的存储过程:
DELIMITER $$
CREATE DEFINER=`vidhu`@`%` PROCEDURE `test`(var_datain TEXT)
BEGIN
SELECT var_datain;
END
When calling this procedure in mysql-workbench it returns the data I put in:
在 mysql-workbench 中调用此过程时,它返回我输入的数据:


Now when I call it from PHP using pdoI get an error:
现在,当我使用pdo从 PHP 调用它时,出现错误:
Fatal error: Cannot pass parameter 2 by reference in C:/apache......(3rd line)
Here is my php code:
这是我的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];
回答by Corbin
You need to use bindValueinstead of bindParam.
When you use bindParam, it binds the variable provided to the parameter, not the value of the variable.
当您使用 bindParam 时,它绑定提供给参数的变量,而不是变量的值。
So, if you do:
所以,如果你这样做:
$x = 5;
$stmt->bindParam(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 6 instead of 5
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).
它实际上是用 6 而不是 5 来执行的。为此,该方法必须具有对变量的引用。你不能引用文字,所以这意味着 bindParam 不能与文字(或任何你不能引用的东西)一起使用。
$x = 5;
$stmt->bindValue(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 5 instead of 6
Then:
然后:
$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
回答by Armando Rodriguez Arguijo
The following code works for calling without prepare statement!
以下代码适用于没有准备语句的调用!
$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;

