从php调用的SqlServer存储过程不能正确返回整数输出

时间:2014-10-28 13:55:07

标签: php sql-server sql-server-2008 stored-procedures output

我试图使用php mssql函数从SQL Server 2008数据库上的存储过程中捕获put。代码运行时没有错误,但是我的输出参数之一得到了一个奇怪的值。

存储过程代码:

CREATE PROCEDURE [dbo].[check_barcode_and_return]
    @Barcode nvarchar(20),
    @IsInDatabase int OUTPUT,
    @Product_Info nvarchar(100) OUTPUT

AS
  SELECT @IsInDatabase = COUNT(*) FROM dbo.product_info WHERE barcode = @Barcode

  DECLARE @Brand varchar(45)
  SET @Brand = (SELECT brand FROM dbo.product_info WHERE barcode = @Barcode)
  DECLARE @Description varchar(50)
  SET @Description = (SELECT product_desc FROM dbo.product_info WHERE barcode = @Barcode) 
  SELECT @Product_Info = @Brand + '_' + @Description
RETURN 

GO

以下是调用它的PHP代码:

<?php
  // use a barcode known to be present in database
  $barcode_yes = '11335577';
  // use a sbarcode known NOT to be in database
  $barcode_no = '0011223344';
  $host = '00.000.000.000';
  $db = 'dbName';
  $user = 'username';
  $password = 'password';
  $barcodeInDB = 0;
  $productInfo = "";
  try {
    $conn = mssql_connect($host, $user, $password);
    mssql_select_db($db, $conn);
    $stmt = mssql_init('check_barcode_and_return', $conn);
    mssql_bind($stmt, '@Barcode', $barcode_yes, SQLVARCHAR, false, false, 20);
    mssql_bind($stmt, '@IsInDatabase', $barcodeInDB, SQLINT1, true, false, 1);
    mssql_bind($stmt, '@Product_Info', $productInfo, SQLVARCHAR, true, false, 100);
    mssql_execute($stmt, true);
    echo 'positive test results:'."\n";
    echo 'output $barcodeInDB = '.$barcodeInDB."\n";
    echo '$productInfo = '.$sampleInfo."\n";

    //reset for next call
    mssql_free_statement($stmt);
    $barcodeInDB = 0;
    $productInfo = "";

    $stmt = mssql_init('check_barcode_and_return', $conn);
    mssql_bind($stmt, '@Barcode', $barcode_no, SQLVARCHAR, false, false, 20);
    mssql_bind($stmt, '@IsInDatabase', $barcodeInDB, SQLINT1, true, false, 1);
    mssql_bind($stmt, '@Product_Info', $productInfo, SQLVARCHAR, true, false, 100);
    mssql_execute($stmt, true);
    echo 'negative test results:'."\n";
    echo 'output $barcodeInTable = '.$barcodeInDB."\n";
    echo '$productInfo = '.$productInfo."\n";

    mssql_close($conn);
  } 
  catch (Exception $e) {
    echo $e->getMessage();
  }
?>

当我从命令行运行它时,结果如下:

positive test results:
output $barcodeInDB = 968529665
$productInfo = Heinz_tomato ketchup
negative test results:
output $barcodeInTable = 968529664
$productInfo = _

如果我直接使用SQL Server Management Studio运行存储过程,输入上面使用的条形码,我会得到 @BarcodeInDB = 1 进行肯定测试, @BarcodeInDB = 0 对于负面的。

代码位于运行 Ubuntu with php5.3.10 的Linux服务器上。

我需要更改什么才能获得整数输出参数的正确值?

1 个答案:

答案 0 :(得分:0)

我需要将输出参​​数绑定为SQLINT4的整数数据类型,因为显然,T-SQL整数变量是4字节整数。试图强制它们进入容量较小的数据类型(即SQLINT1,SQLINT2或SQLBIT)会导致不可预测的输出。

所以,我改为......

...
mssql_bind($stmt, '@IsInDatabase', $barcodeInDB, SQLINT4, true);
...

它工作正常。