Home >Database >Mysql Tutorial >How to Effectively Store .pdf Files as BLOBs in MySQL Using PHP?

How to Effectively Store .pdf Files as BLOBs in MySQL Using PHP?

DDD
DDDOriginal
2024-10-24 04:18:02276browse

How to Effectively Store .pdf Files as BLOBs in MySQL Using PHP?

Effective Storage of .pdf Files in MySQL BLOBs Utilizing PHP

Storing binary large objects (BLOBs) such as .pdf files within MySQL databases using PHP raises questions regarding the optimal approach. In this article, we'll delve into a robust solution to this common challenge.

Solution:

Assuming you have a database table with an ID and a DATA column for storing BLOBs, consider employing the following technique:

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

Considerations:

Storing BLOBs in databases poses potential drawbacks such as table bloat and challenges in efficient retrieval. Hence, a recommended strategy is to relocate the file to a file system location and store its path in the database for retrieval purposes.

Deprecation and Modern Alternatives:

Please note that the provided code is outdated and unsuitable for PHP 7 and later versions. It is strongly advised to adopt modern database access methods like mysqli or PDO instead of the deprecated mysql_* functions.

mysqli Example:

Using mysqli in procedural mode, you can achieve the same functionality with the following code:

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

Preferred Approach:

For optimal performance and security, consider leveraging MySQLI or PDO prepared statements for inserting BLOBs into your MySQL database. This ensures both efficiency and protection against SQL injection attacks.

The above is the detailed content of How to Effectively 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