Inserting a PDF into a MSQL database with PHP
April 9, 2009
I have in the past inserted images and other binary data into a MYSQL database using PHP with no problems. However now at my current job we needed to insert PDF’s into a MSQL server. Unfortunately google turns up relatively little searches on inserting binary data into MSQL database via PHP. Luckily after doing some serious research I’ve found a solution that works.
Normally with MYSQL you would open the file for reading and use addslashes to escape characters.
// Escape special characters in the file
$fileContents = AddSlashes($fileContents);
Unfortunately with MSQL you can’t do this. In order to store binary data you must use unpack().
$fileContents = file_get_contents($userfile);
$fileContents1 = unpack(“H*hex”, $fileContents);
$fileContents2 = “0x”.$fileContents1[hex];
Using this code you will properly read the binary data into a string that can then be inserted into the MSQL database. Oh and one more thing. When doing the insertion you need to concatenate the $fileContents2 in your sql statement. Otherwise it will not work.
‘$fileContents2 ‘ will not work.
\”$fileContents2\” will not work.
“.$fileContents2 .” works properly
For whatever reason the PDF docs I inserted came back as corrupted when pulled out of the database.
Hopefully this will help those of you trying to insert an image or other binary data into a MSQL database using PHP.
Got something to say?
You must be logged in to post a comment.


