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


PHP mysqli prepared statement for stored procedure with out parameter

我有一个存储过程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$$

我想使用mysqli准备的语句从PHP调用它。我是按照代码片段来做的,但它给了我警告。

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

INOUT/OUT参数

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

所以你可以用

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