В следующем примере показано, как вставить файл PDF в столбец varbinary (max) в SQL Server, а затем сохранить этот файл на диск:
T-SQL:
CREATE TABLE [dbo].[VarbinaryTable] (
[Data] varbinary(max) NULL
)
PHP:
<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
$cinfo = array(
"Database" => $database,
"UID" => $uid,
"PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false)
{
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
# Insert PDF file
$pdf = file_get_contents('PDFFile.pdf');
$sql = "INSERT INTO VarbinaryTable ([Data]) VALUES (?)";
# In your case:
# $sql = "UPDATE VarbinaryTable SET [Data] = ? WHERE ID = 1";
$params = array(
array($pdf, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'))
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error insert (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
# Get PDF file and save it again on disk.
$sql = "SELECT [Data] FROM VarbinaryTable";
# In your case:
# $sql = "SELECT [Data] FROM VarbinaryTable WHERE ID = 1";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
if (sqlsrv_fetch($stmt)) {
$pdf = sqlsrv_get_field($stmt, 0, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
file_put_contents('PDFFile-fromDB.pdf', $pdf);
}
# Output the file
header('Content-Description: File Transfer');
header("Content-type: application/pdf");
header("Content-disposition: attachment; filename=PDFFile-fromDB.pdf");
header('Content-Length: ' . filesize("PDFFile-fromDB.pdf"));
readfile("PDFFile-fromDB.pdf");
?>