PHP mysqli为带有out参数的存储过程准备了语句

我有一个存储过程IsUserPresent像:

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$$

我想用PHP调用它来使用MysqLi预编译语句.我是在代码片段之后做的,但它给了我警告.

$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 manual声明你必须使用会话变量(MysqL会话,而不是PHP)

INOUT/OUT parameter

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参数的函数.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...