Insert binary data into SQL Server using PHP

跟風遠走 提交于 2019-12-07 03:46:18

问题


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.


回答1:


The simple answer is: stop what you're doing.

You don't want to store binary files inside a database unless you have some very specific security issues. Instead you want to store their filenames (possibly rename the files to prevent confliction) and then store that in the database. If security is an issue, then put them in a non web folder and use your code to retrieve the file and only serve the file if the user has access to it.

Storing images or files inside a database is a waste of file space, a mis-use of databases, and not letting things do what they do best; the filesystem knows files, the database knows data.




回答2:


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




回答3:


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?



来源:https://stackoverflow.com/questions/689735/insert-binary-data-into-sql-server-using-php

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