如何使用PHP将.pdf文件作为BLOB存储到MySQL中? [英] How to store .pdf files into MySQL as BLOBs using PHP?

查看:274
本文介绍了如何使用PHP将.pdf文件作为BLOB存储到MySQL中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从PHP将.pdf文件作为BLOB存储到MySQL中?

How to store .pdf files into MySQL as BLOBs from PHP?

推荐答案

编辑后添加:以下代码已过时,在PHP 7中不起作用.回答以获取更多详细信息.

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.

假设一个具有整数ID和一个blob DATA列的表结构,并假设使用MySQL函数与数据库进行接口,则您可能会执行以下操作:

Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

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

警告一下,通常不认为将blob存储在数据库中是最好的主意,因为它可能导致表膨胀,并伴有许多其他问题.更好的方法是将文件移动到可以检索的文件系统中的某个位置,并将该文件的路径而不是文件本身存储在数据库中.

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

此外,不建议使用mysql_ *函数调用,因为这些方法已被有效弃用,并且实际上并不是考虑使用高于4.x的MySQL版本构建的.您应该改为使用mysqli或PDO.

更新:mysql_ *函数在PHP 5.x中已被弃用,并且在PHP 7中已被完全删除!!切换到更现代的数据库抽象(MySQLI,PDO).由于历史原因,我决定保留上面的原始答案,但实际上不使用它

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

以下是在程序模式下使用mysqli的方法:

Here's how to do it with mysqli in procedural mode:

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

最理想的方法是使用MySQLI/PDO准备好的语句.

The ideal way of doing it is with MySQLI/PDO prepared statements.

这篇关于如何使用PHP将.pdf文件作为BLOB存储到MySQL中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆