Storing PDF Files as BLOBs in MySQL with PHP
Storing binary large objects (BLOBs) like PDF files in databases can be useful in certain scenarios. This article explores how to store PDF files as BLOBs in MySQL using PHP.
Inserting PDF Files into MySQL
To insert a PDF file into a MySQL table as a BLOB, you can use the following steps:
Example Code
The following PHP code snippet demonstrates how to store a PDF file in a MySQL table:
<code class="php">$fileContents = file_get_contents('/path/to/file.pdf'); $escapedFileContents = mysql_real_escape_string($fileContents); $query = 'INSERT INTO files (name, data) VALUES ("pdf_file", "' . $escapedFileContents . '");'; $result = mysql_query($query);</code>
Note on Obsolescence
It's important to note that MySQL functions like mysql_query aredeprecated and should not be used in new code. As of PHP 7, MySQL functions have been removed. Instead, use MySQLi or PHP Data Objects (PDO) for database interactions. The updated examples in the answer reflect these changes.
Considerations
While storing files as BLOBs in databases can be convenient, it's generally not the best practice. BLOBs can lead to table bloat and performance issues. A preferable approach is to store the file path in the database and store the file itself on the filesystem.
The above is the detailed content of How to Store PDF Files as BLOBs in MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!