I try to get the output value of a MySQL stored procedure with PHP. I found some similar questions here on StackOverflow, but none of them helped.
Based on my researches, I found two ways of how to achieve this goal, however, none of them worked so far. The procedure's output is simply not caught, no matter how I tried.
FIRST ATTEMPT:
In the following case, I set AAA as the default value for the variable @name, then I pass it as a parameter to the stored procedure jani(). In the procedure, I change the value of the in-output variable to BBB, so I expect the passed AAA to be changed to BBB. Then I select the variable and try to display the result value, however, the value remains AAA.
My code:
// DEFINING THE PROCEDURE:
$sql = '
DROP PROCEDURE IF EXISTS jani;
CREATE PROCEDURE jani (
INOUT output VARCHAR(3)
)
BEGIN
SET @output = "BBB";
END';
$oDb->exec($sql);
// DEFINING THE VARIABLE TO CATCH THE OUTPUT:
$sql = 'SET @name = "AAA"';
$do = $oDb->prepare($sql);
$do->execute();
// CALLING THE PROCEDURE AND TRYING TO CATCH THE OUTPUT:
$sql = 'CALL jani(@name)';
$do = $oDb->prepare($sql);
$do->execute();
// SELECTING THE (HOPEFULLY UPDATED) VARIABLE:
$sql = 'SELECT @name name';
$do = $oDb->prepare($sql);
$do->execute();
// DISPLAYING THE RESULT:
var_dump($do->fetchObject());
SECOND ATTEMPT:
I also followed tutorials like this here without success. The source claims that $do->bindParam() should work, but it did not help in my case. The value of the variable is still unchanged. My code implementing the second solution:
// DEFINING THE PROCEDURE:
$sql = '
DROP PROCEDURE IF EXISTS jani;
CREATE PROCEDURE jani (
INOUT output VARCHAR(3)
)
BEGIN
SET @output = "BBB";
END';
$oDb->exec($sql);
// SETTING DEFAULT VARIABLE VALUE:
$name = 'AAA';
// CALLING THE PROCEDURE AND BINDING THE VARIABLE TO ITS PARAMETER:
$sql = 'CALL jani(?)';
$do = $oDb->prepare($sql);
$do->bindParam(1, $name, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 3);
$do->execute();
// DISPLAYING THE RESULT (which is still "AAA" unfortunately):
echo $name;
Both cases return the unmodified value AAA instead of the procedure output BBB. What am I doing wrong?
Thanks in advance for all the helping comments and answers :) Have a nice day!
$sql = 'SET @name = "AAA"; CALL jani(@name); SELECT @name name;', then execute it.var_dump()result is eitherbool(false)(in case I use$do->fetchObject()) orarray(0) { }(in case I use$do->fetchAll()) @user9335240SELECTstatement, then the desired value returned. Despite I could make it work there, my PHP code still could not get the output value from the stored procedure, so the result stayed NULL :(