在PHP中使用带有存储过程的pdo [英] Using pdo in php with stored procedure

查看:113
本文介绍了在PHP中使用带有存储过程的pdo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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];

推荐答案

您需要使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆