Home  >  Article  >  Database  >  How to Store PDF Files as BLOBs in MySQL Using PHP?

How to Store PDF Files as BLOBs in MySQL Using PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 03:52:02242browse

How to Store PDF Files as BLOBs in MySQL Using PHP?

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:

  1. Establish a database connection. Use MySQL functions like mysql_connect or MySQL Improved Extension (MySQLi) to connect to the database.
  2. Prepare the SQL query. Create an SQL INSERT statement that includes aBLOB column to store the file data.
  3. Escape the file contents. To prevent SQL injection, use PHP's mysql_real_escape_string function (or mysqli_real_escape_string) to escape the file's contents before inserting them into the database.
  4. Execute the query. Use mysql_query or mysqli_query to execute the INSERT statement.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn