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:
$result = mysql_query('INSERT INTO table (
data
) VALUES (
\'' . mysql_real_escape_string(file_get_contents('/path/to/the/file/to/store.pdf')) . '\'
);');
Caution: Using the mysql_* functions is discouraged, as they are deprecated. Consider using mysqli or PDO instead.
For PHP 5.x and earlier:
$result = mysqli_query($db, 'INSERT INTO table (
data
) VALUES (
\'' . mysqli_real_escape_string(file_get_contents('/path/to/the/file/to/store.pdf'), $db) . '\'
);');
For PHP 7 and later:
Prepared statements are the recommended approach for storing binary data in MySQL:
$stmt = $mysqli->prepare('INSERT INTO table (
data
) VALUES (?)');
$stmt->bind_param('b', file_get_contents('/path/to/the/file/to/store.pdf'));
$stmt->execute();
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3