0

I'm working with MS SQL 2005 and PHP, and I got this code

move_uploaded_file($_FILES["file"]["tmp_name"],"temp/" . $_FILES["file"]["name"]);
$data = fopen("temp/"$_FILES["file"]["name"], "rb");
$content =fread($data,$_FILES['file']['size']);
$content=addslashes($content);
$sql = "INSERT INTO docs(file) value($content)";
if(!mssql_query($sql)){
    die('MSSQL error: ' . mssql_get_last_message());
}

and I got this error: MSSQL error: Incorrect syntax near 'PDF'

PD: excuse my poor english


I found the solution: the code would look like:

function mssql_escape($data) {
    if(is_numeric($data))
      return $data;
    $unpacked = unpack('H*hex', $data);
    return '0x' . $unpacked['hex'];
}

-

move_uploaded_file($_FILES["file"]["tmp_name"],"temp/" . $_FILES["file"]["name"]);
$data = fopen("temp/"$_FILES["file"]["name"], "rb");
$content =fread($data,$_FILES['file']['size']);
$content=mssql_escape($content);//Call mssql_escape function
$sql = "INSERT INTO docs(file) value($content)";
if(!mssql_query($sql)){
    die('MSSQL error: ' . mssql_get_last_message());
}
milo
  • 132
  • 2
  • 9

2 Answers2

0

Use parameters. See the documentation - specifically the first example for mssql_bind - for instructions on how to do that.

You're trying to insert the contents of the PDF file as a string, and you have no quotes around that string. But even if you wrap $contents in quotes, it probably still will not work. There may be binary in the file contents that simply cannot be inserted in this way.

Also, it may be easier to just save the PDF file somewhere in your filesystem and save the path to the file in your database. That way you won't have huge (megabytes!) records in your database and the files will probably be quicker to access.

Kryten
  • 15,230
  • 6
  • 45
  • 68
0

I found the solution: the code would look like:

function mssql_escape($data) {
    if(is_numeric($data))
      return $data;
    $unpacked = unpack('H*hex', $data);
    return '0x' . $unpacked['hex'];
}

-

move_uploaded_file($_FILES["file"]["tmp_name"],"temp/" . $_FILES["file"]["name"]);
$data = fopen("temp/"$_FILES["file"]["name"], "rb");
$content =fread($data,$_FILES['file']['size']);
$content=mssql_escape($content);//Call mssql_escape function
$sql = "INSERT INTO docs(file) value($content)";
if(!mssql_query($sql)){
    die('MSSQL error: ' . mssql_get_last_message());
}
milo
  • 132
  • 2
  • 9