Home  >  Article  >  Database  >  How to Store PDF Files as MySQL BLOBs in PHP (With Code Examples)?

How to Store PDF Files as MySQL BLOBs in PHP (With Code Examples)?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 19:49:01960browse

How to Store PDF Files as MySQL BLOBs in PHP (With Code Examples)?

Storing PDF Files as MySQL BLOBs with PHP

When storing PDF files as BLOBs (Binary Large Objects) in MySQL using PHP, it's recommended to consider the potential drawbacks of storing binary data in a database. However, if you choose to do so, here's how you can approach it:

Firstly, define a table with an integer ID field and a BLOB column named DATA.

To store a PDF file, use the following query:

<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>

Caution: Using the mysql_* functions is discouraged, as they are deprecated. Consider using mysqli or PDO instead.

For PHP 5.x and earlier:

<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>

For PHP 7 and later:

Prepared statements are the recommended approach for storing binary data in MySQL:

<code class="php">$stmt = $mysqli->prepare('INSERT INTO table (
    data
) VALUES (?)');

$stmt->bind_param('b', file_get_contents('/path/to/the/file/to/store.pdf'));

$stmt->execute();</code>

The above is the detailed content of How to Store PDF Files as MySQL BLOBs in PHP (With Code Examples)?. 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