简体   繁体   中英

INOUT parameter failure for stored procedure called from prepared statement

Here's my stored procedure:

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `testProc`(INOUT num INT(11), INOUT num2 INT(11))
BEGIN
    set num2 = num+7;
END

Here's the code that calls it:

$newId = 1;
$type - 2;

if ($stmt = mysqli_prepare($con, 'call testProc(?,?)')) {
    mysqli_stmt_bind_param($stmt, 'ii', $type,$newId);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $type,$newId);
    echo $newId;
    exit;
    }

I expected $newId to hold 9. It still holds 1.

mysqli_stmt_bind_result() seems redundant, as I don't actually have a result set (and I think its existence causes bugs later because I don't have a result set), but this code falls over without it (My actual code doesn't but I don't know why). That's may be moot though.

Please can anyone show me how to change this code to make it work?

The PHP manual states that you've got to use session variables (MySQL sessions, not PHP)

INOUT/OUT parameter

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

mysqli_stmt_bind_result() is to be used to bind values from a resultset like a SELECT statement. This could be a SELECT statement in a stored procedure, see the chapter Stored Routine Syntax of the MySQL manual:

MySQL supports a very useful extension that enables the use of regular SELECT statements (that is, without using cursors or local variables) inside a stored procedure. The result set of such a query is simply sent directly to the client.

So you could do it with

// set your IN parameter using a prepared statement
if ($stmt = mysqli_prepare($con, 'SET @type := ?')) {
    mysqli_stmt_bind_param($stmt, 'i', $type);
    mysqli_stmt_execute($stmt);
}

// do the same for your second parameter 
if ($stmt = mysqli_prepare($con, 'SET @newId := ?')) {
    mysqli_stmt_bind_param($stmt, 'i', $newId);
    mysqli_stmt_execute($stmt);
}

// No need to use a prepared statement for the procedure call anymore
$result = mysqli_query($con, 'call testProc(@type, @newId)');
// If the procedure would return something else than the INOUT or OUT parameter
// then you would get this result now

// getting the value of the INOUT parameter
$result = mysqli_query($con, 'SELECT @newId as newId');
$row = mysqli_fetch_assoc($result);             
var_dump($row);

Output:

Connected to databasearray(1) {
  ["newId"]=>
  string(1) "9"
}

Note: Error handling left as an exercise to show only the main issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM