[英]UPDATE VARBINARY(MAX) column in SQL Server table with $_FILE image upload
I've been looking all across the internet for help on this and have found nothing. 我一直在互联网上寻找有关此方面的帮助,却一无所获。
Basically I need to know how to update a SQL Server VARBINARY(MAX)
column with the hex of an image uploaded from a HTML form. 基本上,我需要知道如何使用从HTML表单上传的图像的十六进制更新SQL Server
VARBINARY(MAX)
列。 The database is in a different place to the HTML form, so move_uploaded_file
in PHP then OPENROWSET (BULK ...)
in SQL doesn't work (unable to find the file). 数据库与HTML表单的位置不同,因此PHP中的
move_uploaded_file
然后SQL中的OPENROWSET (BULK ...)
不起作用(无法找到文件)。
I also tried doing file_get_contents
on the uploaded $_FILE['name_']['tmp_name']
, then used unpack("H*hex")
and put the result of that into the SQL column with a "0x" prepend, but that crashes, saying it needs to be converted from a VARCHAR
to a VARBINARY
. 我还尝试在上传的
$_FILE['name_']['tmp_name']
上执行file_get_contents
,然后使用unpack("H*hex")
并将结果放入带有“ 0x”前缀的SQL列中,但是崩溃,表示需要将其从VARCHAR
转换为VARBINARY
。 When I convert it, the code runs and the column is populated, but the image is malformed. 当我转换它时,代码运行并且填充了列,但是图像格式不正确。
No idea what to do next. 不知道下一步该怎么做。 Pls help.
请帮助。
Solution: 解:
This is a basic approach using PHP Driver for SQL Server : 这是使用PHP Driver for SQL Server的基本方法:
Table creation (T-SQL) : 表创建(T-SQL) :
CREATE TABLE [dbo].[ImageTable] (
[ImageData] varbinary(max) NULL
)
PHP: 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;
}
# Update image using CONVERT()
$image = file_get_contents('image.jpg');
$sql = "UPDATE ImageTable SET [ImageData] = CONVERT(varbinary(max), ?) WHERE (yor_update_condition)";
$params = array(
array($image, SQLSRV_PARAM_IN)
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
# End
echo 'Image updated.'
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.