Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store .pdf files into MySQL as BLOBs using PHP?

Tags:

php

mysql

pdf

How to store .pdf files into MySQL as BLOBs from PHP?

like image 971
xcodemaddy Avatar asked Jan 27 '11 07:01

xcodemaddy


People also ask

Can PDF be stored as BLOB?

MySQL has the BLOB datatype that can be used to store files such as . pdf, . jpg, .

Can we store PDF in MySQL database?

A Binary Large Object ( BLOB ) is a MySQL data type that can store binary data such as images, multimedia, and PDF files.

Can PDF be stored in database?

You can store the PDF inside of a table using a varbinary field and an extension field. Then you can take advantage of the Fulltext serch engine to search inside of the PDFs. You will have to install a PDF iFilter in your SQL server.

How does MySQL store blobs?

Blobs are stored logically with a row. This means if you DELETE the row, the associated blob is deleted automatically. But if you store the blob outside the database, you end up with orphaned blob files after you delete rows from the database. You have to do manual steps to find and delete these files.


1 Answers

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

like image 132
GordonM Avatar answered Sep 20 '22 19:09

GordonM