PHP mysqli 为没有参数的存储过程准备的语句 [英] PHP mysqli prepared statement for stored procedure with out parameter

查看:22
本文介绍了PHP mysqli 为没有参数的存储过程准备的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储过程 IsUserPresent,例如:

I have a stored procedure IsUserPresent like:

DELIMITER $$
CREATE PROCEDURE IsUserPresent(
    in userid varchar (150),
    out isPresent bit
)
BEGIN
    SET isPresent=0;
    SELECT COUNT(*)
    INTO isPresent
    FROM users_table
    WHERE users_table.userid=userid;
END$$

我想使用 mysqli 准备好的语句从 PHP 调用它.我正在按照代码片段执行此操作,但它给了我警告.

and I want to call it from PHP using mysqli prepared statement. I am doing it following code snippet but it gives me warning.

$connect=&ConnectDB();
$stmt=$connect->prepare("CALL IsUserPresent(?,?)");
$stmt->bind_param('si',$uid,$userCount);
$stmt->execute();
$toRet = $userCount!=0;
Disconnect($connect);
return $toRet;

警告如下:

Premature end of data (mysqlnd_wireprotocol.c:1112)
Warning: mysqli_stmt::execute(): RSET_HEADER packet 1 bytes shorter than expected
Warning: mysqli_stmt::execute(): Error reading result set's header

推荐答案

存储过程与准备好的语句一起工作的方式有点复杂.PHP 手册 指出您必须使用会话变量(MySQL 会话,而不是 PHP)

The way stored procedures work with prepared statements is a bit more complicated. PHP manual states that you've got to use session variables (MySQL sessions, not PHP)

INOUT/OUT 参数

INOUT/OUT parameter

使用会话变量访问 INOUT/OUT 参数的值.

The values of INOUT/OUT parameters are accessed using session variables.

所以你可以用

$connect=&ConnectDB();
// bind the first parameter to the session variable @uid
$stmt = $connect->prepare('SET @uid := ?');
$stmt->bind_param('s', $uid);
$stmt->execute();

// bind the second parameter to the session variable @userCount
$stmt = $connect->prepare('SET @userCount := ?');
$stmt->bind_param('i', $userCount);
$stmt->execute();

// execute the stored Procedure
$result = $connect->query('call IsUserPresent(@uid, @userCount)');

// getting the value of the OUT parameter
$r = $connect->query('SELECT @userCount as userCount');
$row = $r->fetch_assoc();               

$toRet = ($row['userCount'] != 0);

备注:

我建议将此过程重写为带有一个返回 INT 的 IN 参数的函数.

I recommend to rewrite this procedure as a function with one IN parameter that returns INT.

这篇关于PHP mysqli 为没有参数的存储过程准备的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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