Background
Development environment:
PHP 7.0.3 with Apache 2.4.16 for Windows 10 x64
SQL Server 2014 Standard
The section has a FileStream for the corresponding columns of the file.
I tried installing the sqlsvr driver, but failed due to lack of support for PHP7
Access SQL Server from ODBC Using the SQL Server Driver
PHP code to insert image data in MSSQL
$link = @new \PDO("odbc:Driver={SQL Server};Server=$server;Database=$db", $user, $password); $stmt = $link->prepare("INSERT INTO [Attachment] (AttID, Seq , ModuleCde, AppID, StaffID , FileName , [File]) VALUES ( NEWID() , ? , ? , ? , ? , ? , ? )"); $stmt->bindValue(1,$_POST["Seq"],PDO::PARAM_INT); $stmt->bindValue(2,$_POST["ModuleCde"],PDO::PARAM_STR); $stmt->bindValue(3,$_POST["AppID"],PDO::PARAM_STR); $stmt->bindValue(4,$_SESSION["StaffID"],PDO::PARAM_STR); $stmt->bindValue(5,$_FILES["file"]["name"][$_POST["Seq"]],PDO::PARAM_STR); $stmt->bindValue(6,file_get_contents($_FILES["file"]["tmp_name"][$_POST["Seq"]]),PDO::PARAM_STR); $stmt->execute();
PHP code to save image data from MSSQL
$link = @new \PDO("odbc:Driver={SQL Server};Server=$server;Database=$db", $user, $password); $stmt = $link->prepare("SELECT DATALENGTH([File]) AS [Size] , CONVERT(NVARCHAR(MAX),[File],2) AS [File] FROM [Attachment] WHERE [ModuleCde] = ? AND [AppID] = ? AND [Seq] = ? AND [StaffID] = ?"); $stmt->bindValue(1,$_GET["ModuleCde"],PDO::PARAM_STR); $stmt->bindValue(2,$_GET["AppID"],PDO::PARAM_STR); $stmt->bindValue(3,$_GET["Seq"],PDO::PARAM_STR); $stmt->bindValue(4,$_SESSION["StaffID"],PDO::PARAM_STR); $stmt->execute(); $stmt->bindColumn(2,$img,PDO::PARAM_LOB, 0); $stmt->fetch(PDO::FETCH_ASSOC); file_put_contents( "file" , $img );
The file was successfully uploaded to the SQL server. Opening the DATA SQL Server directory, all downloaded files and it can be opened with Paint.
But extracting the file from the above image save code is corrupt. The file is missing some bytes from the original.
I tried the method
fwrite( fopen("file","w+") , strtolower("0x".str_replace("\0","",$img)) );
as well as the method specified in this link.
Php with MSSQL displays raw data from varbinary field
But both were unlucky, the file also seemed to be corrupted.
Any help is appreciated.
Change 2016-02-25
The SQL statement has been changed as follows, but the output file is still corrupt.
$link->prepare("SELECT DATALENGTH([File]) AS [Size] , [File] FROM [Attachment] WHERE [ModuleCde] = ? AND [AppID] = ? AND [Seq] = ? AND [StaffID] = ?");
Now I'm trying to change another ODBC SQL server driver to check if the file can be successfully output.
Change 2016-08-09
With the updated MSSQL PDU driver for PHP 7. Everything worked again with charm.
Now we no longer need to convert varbinary data to use this new driver.
Link Link