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!