PHP 获取存储过程的 return 值

PHP get return value of stored procedure

我很高兴通过 PDO 使用 SQL 服务器来处理遗留 PHP 应用程序。

如何在 PHP 中检索使用 RETURN 语句作为输出通道的存储过程的 return 值?

示例程序

CREATE PROCEDURE [dbo].[mleko_test]
    @param INT
AS
  BEGIN
    RETURN @param * 3;
  END
GO

如果可以的话,我宁愿不修改程序。


我知道有类似的问题,但他们不包括这种情况

像这样执行存储过程:"exec ?=mleko_test(?)".

工作示例:

<?php
#------------------------------
# Connection info
#------------------------------
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';

#------------------------------
# With PDO
#------------------------------
try {
    $conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
    die ( "Error connecting to SQL Server" );
}

try {
    $sql = "exec ? = mleko_test (?)";
    $param = 3;
    $spresult = 0;
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(1, $spresult, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
    $stmt->bindParam(2, $param);
    $stmt->execute();
} catch ( PDOException $e ) {
    die ( "Error connecting to SQL Server" );
}

$stmt = null;
$conn = null;

echo 'Stored procedure return value (with PDO): '.$spresult."</br>";

#------------------------------
# Without PDO
#------------------------------
$cinfo = array (
    "Database" => $database,
    "UID" => $uid,
    "PWD" => $pwd
);

$conn = sqlsrv_connect($server, $cinfo);
if ( $conn === false )
{
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

$sql = "exec ? = mleko_test (?)";
$param = 3;
$spresult = 0;
$params = array(   
    array(&$spresult, SQLSRV_PARAM_OUT), 
    array($param, SQLSRV_PARAM_IN),  
); 
$stmt = sqlsrv_query($conn, $sql, $params);
if ( $stmt === false ) {
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
}

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

echo 'Stored procedure return value (without PDO): '.$spresult."</br>";
?>

备注:

使用 PHP 7.1.12 和 PHP 驱动程序测试 SQL 服务器(pdo_sqlsrv 版本 4.3.0+9904)。

我找到了使用多查询的解决方案,但 更简洁

<?php
$connection = new PDO($connectionString, $DB_USERNAME, $DB_PASSWORD);

$stmt = $connection->prepare(<<<SQL
DECLARE @a INT;
EXEC @a = mleko_test :in
SELECT @a AS result;
SQL
);

$stmt->execute([":in" => 123]);
echo $stmt->fetch()["result"] . "\n";

我不得不改变

$sql = "exec ?=mleko_test(?)";

为了

$sql = "{?=call mleko_test(?)}";