简体   繁体   English

如何使用 PHP 从 MySQL 数据库中存储和检索图像?

[英]How can I store and retrieve images from a MySQL database using PHP?

How can I insert an image in MySQL and then retrieve it using PHP?如何在 MySQL 中插入图像,然后使用 PHP 检索它?

I have limited experience in either area, and I could use a little code to get me started in figuring this out.我在这两个领域的经验都有限,我可以使用一些代码让我开始弄清楚这一点。

First you create a MySQL table to store images, like for example:首先,您创建一个 MySQL 表来存储图像,例如:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:然后您可以将图像写入数据库,例如:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:您可以在网页中显示数据库中的图像:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

不是将图像存储在数据库中,而是将它们存储在磁盘中的文件夹中,并将它们的位置存储在数据库中。

Beware that serving images from DB is usually much, much much slower than serving them from disk.请注意,从数据库提供图像通常比从磁盘提供图像要慢得多

You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.您将启动一个 PHP 进程,打开一个数据库连接,让数据库从与文件系统相同的磁盘和 RAM 中读取图像数据以进行缓存,将其传输到少数套接字和缓冲区,然后通过 PHP 推出,默认情况下使它不可缓存并增加了分块 HTTP 编码的开销。

OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead. OTOH 现代网络服务器只需几个优化的内核调用(内存映射文件和传递给 TCP 堆栈的内存区域)即可提供图像,因此它们甚至不会复制内存并且几乎没有开销。

That's a difference between being able to serve 20 or 2000 images in parallel on one machine.这就是能够在一台机器上并行处理 20 或 2000 张图像的区别。

So don't do it unless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.所以不要这样做,除非你绝对需要事务完整性(实际上甚至可以通过数据库和文件系统清理例程中的图像元数据来完成)并且知道如何改进 PHP 对 HTTP 的处理以适合图像。

My opinion is, Instead of storing images directly to the database, It is recommended to store the image location in the database.我的看法是,与其将图片直接存入数据库,不如将图片位置存入数据库。 As we compare both options, Storing images in the database is safe for security purpose.当我们比较这两个选项时,出于安全目的,将图像存储在数据库中是安全的。 Disadvantage are缺点是

  1. If database is corrupted, no way to retrieve.如果数据库损坏,则无法检索。

  2. Retrieving image files from db is slow when compare to other option.与其他选项相比,从 db 检索图像文件的速度很慢。

On the other hand, storing image file location in db will have following advantages.另一方面,将图像文件位置存储在 db 中将具有以下优点。

  1. It is easy to retrieve.很容易找回。

  2. If more than one images are stored, we can easily retrieve image information.如果存储了多个图像,我们可以轻松检索图像信息。

我还建议您考虑这一点,然后选择将图像存储在您的文件系统而不是 DB 中。请参见此处: 在 DB 中存储图像 - 是还是不是?

Personally i wouldnt store the image in the database, Instead put it in a folder not accessable from outside, and use the database for keeping track of its location.就我个人而言,我不会将图像存储在数据库中,而是将其放在无法从外部访问的文件夹中,并使用数据库来跟踪其位置。 keeps database size down and you can just include it by using PHP.减少数据库大小,您可以使用 PHP 将其包含在内。 There would be no way without PHP to access that image then没有 PHP 就无法访问该图像

不要将图像存储在数据库中,而是将其存储在您的手机和电脑中,然后使用它的路径,因为它将保存您的数据库

I agree with the basic concept of @Andomar, but would store the actual images on disk to avoid storing large data in SQL.我同意@Andomar 的基本概念,但会将实际图像存储在磁盘上以避免在 SQL 中存储大量数据。 Remember that a large field is 255 chars in SQL.请记住,SQL 中的一个大字段是 255 个字符。 So you'll need to store the images files in Blobs, which work well when you only have a small amount rows (think: hundreds, not millions).因此,您需要将图像文件存储在 Blob 中,当您只有少量行时(想想:数百,而不是数百万),它会很好地工作。 The reasoning is complex, but it's good practice.推理很复杂,但这是一种很好的做法。 Here's how I know:我是这样知道的:

I wrote a large project that stores lots (and lots) of images.我写了一个存储大量(和大量)图像的大型项目。 Always store them on disk to save yourself a SQL headache.始终将它们存储在磁盘上,以免为 SQL 头疼。 If you're worried about a DB corruption leaving you with images you can't "rebuild" into a database, there's an easy fix (besides backing up your SQL table(s) )如果您担心数据库损坏会留下无法“重建”到数据库中的图像,那么有一个简单的修复方法(除了备份您的 SQL 表)

Store your images in a directory tree with directory names that make sense for humans and parsing.将图像存储在目录树中,目录名称对人类和解析有意义。 So storing it by time might look like "/year/month/day/picture.jpg" or by user "/user_id/picture.jpg".所以按时间存储它可能看起来像“/year/month/day/picture.jpg”或用户“/user_id/picture.jpg”。 Use this as a concept, and just store the path in SQL.以此为概念,只需将路径存储在 SQL 中。 This will make your SQL table small and often cacheable and allow your SQL table to be on one server, and your images to be stored on another "server" such as AWS's S3.这将使您的 SQL 表变小并且通常可缓存,并允许您的 SQL 表位于一台服务器上,而您的图像可以存储在另一台“服务器”上,例如 AWS 的 S3。

If you're really paranoid, you can store a file called "{image_name)_meta.json" in the same directory as the image itself.如果你真的很偏执,你可以将一个名为“{image_name)_meta.json”的文件存储在与图像本身相同的目录中。 Fill it with meta data about the image that you normally store in the DB table.用您通常存储在数据库表中的图像的元数据填充它。 If the table corrupts, you can write aa little function that walks through the tree and rebuilds the table from the JSON files.如果表损坏,您可以编写一个遍历树并从 JSON 文件重建表的小函数。 This of course will take up more disk space, but it's pretty cheap (think: AWS's S3).这当然会占用更多的磁盘空间,但它非常便宜(想想:AWS 的 S3)。

There are lots of ways to solve this, but storing large amounts of images in any SQL-type table is rarely a good idea.有很多方法可以解决这个问题,但是在任何 SQL 类型的表中存储大量图像并不是一个好主意。 Exceptions would be displaying hundreds at once, or perhaps lighting-quick retrieval times (instead of sub-second).例外情况是一次显示数百个,或者可能是闪电般的快速检索时间(而不是亚秒级)。

Good luck with your project!祝你的项目好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM