Skip to content

Sqlsrv driver - binary data encoding #287

@jaroslavrehorka

Description

@jaroslavrehorka
  • bug report? yes
  • feature request? no
  • version: 3.2.0

Description

When inserting / updating a binary data to the MSSQL database, the data (output of file_get_contents) cannot be simply inserted as string value, because it rises an encoding issue (Dibi\DriverException An error occurred translating the query string to UTF-16: No mapping for the Unicode character exists in the target multi-byte code page.).

Instead of that, the binary data have to be passed as an parameter to sqlsrv_query (or sqlsrv_prepare) in following format:

array($binaryData, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'));

More informations can be found here https://akrabat.com/some-notes-on-sql-server-blobs-with-sqlsrv/

Steps To Reproduce

Let's say we have following table:

CREATE TABLE dbo.SampleTable (     
	id INTEGER PRIMARY KEY
	imageFile IMAGE NULL
)

Following code should properly create new record, with binary data

$filePath = 'image.jpg';
$data['imageFile'] = file_get_contents($filePath);
$mssqlConnection->insert('SampleTable', $data)->execute()

But the driver returns the mentioned error.

Now I have to use following workaround (I want to use connection from dibi, as well as generated sql query):

$filePath = 'image.jpg';
$binaryData = file_get_contents($filePath);

$data['imageFile'] = '(?)';
$sqlSrvFile = array($binaryData, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'));

$sqlQuery = $mssqlConnection->insert('SampleTable', $data)->__toString();
$sqlsrvConnection = $mssqlConnection->getDriver()->getResource();

$res = sqlsrv_query($sqlsrvConnection, $sqlQuery, array($sqlSrvFile));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions