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

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

问题描述

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

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

推荐答案

EDITED TO ADD:以下代码已过时,无法在 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天全站免登陆