PHP sqlsrv library handling of varbinary data limits

可紊 提交于 2019-12-24 08:20:47

问题


I have a varbinary(8000) database field in SQL Server that I want to pull out. The sqlsrv limit for varbinary data is 8000.

However if I do a select on the data

<?php
$query = "
    SELECT myvarbinary
    FROM   table
    WHERE  id = 48033;
";
$results = sqlsrv_query($this->conn, $query);
return sqlsrv_fetch_array($results, SQLSRV_FETCH_NUMERIC);

Then the sqlsrv_fetch_array gives an error:

PHP Fatal error: Invalid sql_display_size

Truncation solution (works but no use)

If I convert the field to varbinary(4000) then it works, but varbinary(4001) fails:

<?php
$query = "
    SELECT CAST(myvarbinary AS varbinary(4000)) AS myvarbinary
    FROM   table
    WHERE  id = 48033;
";
$results = sqlsrv_query($this->conn, $query);
return sqlsrv_fetch_array($results, SQLSRV_FETCH_NUMERIC);

However this is no use - I'm truncating half the data.

This also implies that for some reason, although the limit is supposed to be 8000, the sqlsrv library is for some reason doubling the value when it checks against the max allowed field size.

MAX solution - will this fully return the 8000 bytes or is it just silently truncating it?

I can also use varbinary(max) which works.

<?php
$query = "
    SELECT CAST(myvarbinary AS varbinary(max)) AS myvarbinary
    FROM   table
    WHERE  id = 48033;
";
$results = sqlsrv_query($this->conn, $query);
return sqlsrv_fetch_array($results, SQLSRV_FETCH_NUMERIC);

In testing the data that gets returned from sqlsrv I can't prove that it is truncating the data or not. So I think this solution works, but I can't be certain.

Can anyone give me a bit more faith that sqlsrv isn't truncating my data down to 4000 bytes?


Edit: This technet documentation indicates that if you want to transfer images larger than 8KB then you should use varbinary(max)

In this section, we examine code in the Example Application that sends an image to the server as a binary stream. The following code opens an image as a stream and then sends the file up to the server in parts up to 8KB at a time:

$tsql = "INSERT INTO Production.ProductPhoto (LargePhoto)
       VALUES (?);
       SELECT SCOPE_IDENTITY() AS PhotoID";
$fileStream = fopen($_FILES['file']['tmp_name'], "r");
$params = array(
   array(
       $fileStream,
       SQLSRV_PARAM_IN,
       SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY),
       SQLSRV_SQLTYPE_VARBINARY('max')
   )
);

来源:https://stackoverflow.com/questions/40889137/php-sqlsrv-library-handling-of-varbinary-data-limits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!