开发者

Saving files to varbinary(max) field? [duplicate]

This question already has answers here: How to escape strings in SQL Server using PHP? (14 answers) Closed 7 years ago.

I've been at this all day and I just can't seem to figure it out. Our client wants us to save their uploaded files into a table in our database (mssql). There is no restriction as to what kind of files they could upload so following the limited knowledge that I had I did a bit of googling and tried the following:

I created this table:

CREATE TABLE files
  (
    id int NOT NULL PRIMARY KEY IDENTITY,
    name varchar(256),
    content varbinary(max) NOT NULL,
    type varchar(30) NOT NULL,
    size int NOT NULL
    table_id INT NOT NULL FOREIGN KEY REFERENCES myTable(id)
   );

And then I try to add content like this:

$newfileName = $_FILES['uploadfile']['name'];
$newtmpName  = $_FILES['uploadfile']['tmp_name'];
$newfileSize = $_FILES['uploadfile']['size'];
$newfileType = $_FILES['uploadfile']['type'];

//need to get the content of the file
$fp = fopen($newtmpName, 'r');
$file_content = fread($fp, filesize($newtmpName));
$file_content = $file_content;
fclose($fp);

$sql = 'INSERT INTO files ([name], [content], [type], [size], [table_id]) VALUES ("'.$newfileName.'",CAST("'.$file_content.'" AS varbinary(max)),"'.$newfileType.'","'.$newfileSize.'","'.$table_id.'")';

but it just doesn't work... I can upload txt files no problem but anything else will just break. I get errors like the following (which are different with every file):

[42000][105] [Microsoft][SQL Server Native Client 10.0][SQL Server]Un开发者_C百科closed quotation mark after the character string '����'. [42000][102] [Microsoft][SQL Server Native Client 10.0][SQL Server]Incorrect syntax near '����'.

Now I figure this is a problem with the content of the file breaking the SQL but I have NO CLUE how to deal with them (or how to convert them into a string that won't break the sql). Any help would be greatly appreciated as I am completely lost with this.

(Yes I know I haven't protected myself from attacks here, but right now I'm just trying to get the basics to work)


Have a look at: How to escape strings in SQL Server using PHP?


In my case with Microsofts sqlsrv-Driver by far the easiest way was working with params! That avoids using quoting in your binary data and it gets into the database just as it...

Code-Snippet:

$sql = "INSERT INTO tablename (binaryImageField) VALUES (CAST (? AS varbinary(max)))";
$params = array($binaryImageData);
sqlsrv_query($con,$sql,$params);


Try using fopen's binary flag (b):

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

Also, I'm not sure you should addslashes your data. I never worked with MSSQL in PHP, so I can't tell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜