Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert binary data into SQL Server using PHP

I have a varbinary(MAX) field in a SQL Server 2005 database. I'm trying to figure out how to insert binary data (ie. an image) into that field using PHP. I'm using ODBC for the connection to the SQL Server database. I have seen a number of examples that explain this for use with a MySql database but I have not been able to get it to work with SQL Server. Thanks.

like image 279
Keith Maurino Avatar asked Mar 27 '09 13:03

Keith Maurino


2 Answers

function prepareImageDBString($filepath)
{
    $out = 'null';
    $handle = @fopen($filepath, 'rb');
    if ($handle)
    {
        $content = @fread($handle, filesize($filepath));
        $content = bin2hex($content);
        @fclose($handle);
        $out = "0x".$content;
    }
    return $out;
}

usage:

$out = prepareImageDBString('/img/myimg.png');
mssql_query("INSERT INTO MyTable(MyImage) VALUES($out) ");

MyImage is SQL Server field where the type is image

like image 172
Permana Avatar answered Nov 11 '22 04:11

Permana


I won't say it's a bad practice, it depends on how big is the image and how your application use it.

If file below 256K in size, store in db is more efficient; More than 1 mb, store in file-system is recommended.

Storing images in SQL Server?

like image 31
KingBowen Avatar answered Nov 11 '22 03:11

KingBowen