Home > Database > Mysql Tutorial > 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
Release: 2024-10-23 19:49:01
Original
1039 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template