PHP PDO (MSSQL) can not get OUPUT parameters

2019-02-24 06:27发布

I'm trying to get OUTPUT using bindParam (PHP PDO). The PHP PDO library is the FreeTDS for MS SQL driver. Whatever I do, I can't seem to get the "OUTPUT" in the the bound params as suggested on php.net. I've verified I can call the EXEC and return a result set (using a select), but the OUTPUT parameters never change.

PHP Code. $this->db is a PDO object

$stmt = $this->db->prepare("EXEC ".$this->db_schema."[".$this->procedure."] :error_num, :error_msg");
$error_num = 0;
$error_msg = '';
$stmt->bindParam(':error_num', $error_num, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$stmt->bindParam(':error_msg', $error_msg, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 2000);
$stmt->execute();
var_dump($stmt);
echo "\nerror_num: $error_num";
echo "\nerror_msg: $error_msg\n\n";

Stored Procedure for test OUTPUT

USE [NGCustom]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [web].[addTest] (
    @error_num int OUTPUT,
    @error_msg VARCHAR(MAX) OUTPUT
)

AS

BEGIN 
SET @error_num = 99
SET @error_msg = 'Error! Oh my gosh!'
END
GO

Output from PHP:

object(PDOStatement)#77 (1) {
  ["queryString"]=>
  string(54) "EXEC [NGCustom].[web].[addTest] :error_num, :error_msg"
}

error_num: 0
error_msg: 

2条回答
可以哭但决不认输i
2楼-- · 2019-02-24 06:49

Your stored procedure is assigning the parameters, but not returning them.

BEGIN 
 SET @error_num = 99
 SET @error_msg = 'Error! Oh my gosh!'
 SELECT @error_num, @error_msg;  --add this line
END
GO
查看更多
Evening l夕情丶
3楼-- · 2019-02-24 07:02

AFAIK, the FreeTDS driver does not support OUTPUT parameters. I remember this from when my team was doing our assessment.

Here's why it doesn't work: http://www.freetds.org/faq.html#ms.output.parameters

EDIT: Here's a reference from pyodbc (which also runs on FreeTDS), so the same applies: https://code.google.com/p/pyodbc/wiki/StoredProcedures

To quote: "Results: Since we can't use output parameters at this point, you'll need to return results in a result set. Usually this means just ending your stored procedure with a SELECT statement."

You'll need to use a SELECT instead.

查看更多
登录 后发表回答