PHP sqlsrv insert/read blob (varbinary) field from database example

半腔热情 提交于 2019-12-24 05:18:13

问题


I will post this sample for anybody who need help with insert file to varbinary(max) field in sqlsrv DB. Also if you need to read from varbinary field, you can see how I made that. This code is working but all your comments and suggestions are welcome. This is sample table:

CREATE TABLE [dbo].[files]
(
[id] [int] NOT NULL IDENTITY(1, 1),
[content] [varbinary] (max) NULL,
[filename] [varchar] (max) COLLATE Croatian_CI_AS NULL
)

First enter your data for server that you use. If you need to insert file in varbinary field in db:

<?php
$server = "";
$konekcionistring = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$konekcija = sqlsrv_connect( $server, $konekcionistring);

$newfileName = 'testX.pdf';
$newtmpName  = 'C:\xampp\htdocs\testX.pdf';

$fp = fopen($newtmpName, 'rb');
$file_content = fread($fp, filesize($newtmpName));
fclose($fp);

$sql = "INSERT INTO files ([content],[filename]) SELECT CONVERT(VARBINARY(MAX),?),?";

$parametri = array(
                array($file_content),
                array($newfileName)
                );
$r_blob = sqlsrv_query($konekcija, $sql, $parametri);

if( $r_blob === false) 
    {
      die( print_r( sqlsrv_errors(), true) );
    }
?>

When you need to read data from varbinary filed in DB you can use this code:

<?php
$server = "";
$konekcionistring = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$konekcija = sqlsrv_connect( $server, $konekcionistring);

$skript = "SELECT F.content, F.filename AS Template FROM dbo.files AS F";

$izvrsiSQL = sqlsrv_query($konekcija, $skript);
$result = sqlsrv_fetch_array($izvrsiSQL, SQLSRV_FETCH_ASSOC);
$filename = $result['filename'];
$X = $result['content'];


header("Content-type:application/pdf");
header('Content-Disposition: attachment inline; filename="'.$filename.'"');
echo $X;
?>

If you have any comments or suggestions you are welcome.

来源:https://stackoverflow.com/questions/41631765/php-sqlsrv-insert-read-blob-varbinary-field-from-database-example

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