使用 php 在 MySql 数据库中插入 Blob

2022-08-30 21:34:46

我试图在数据库中存储图像,由于某种原因它似乎不起作用。这是我的表的结构。

mysql> describe ImageStore;
+---------+----------+------+-----+---------+-------+
| Field   | Type     | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| ImageId | int(11)  | NO   | PRI | NULL    |       |
| Image   | longblob | NO   |     | NULL    |       |
+---------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

这是我的查询,它插入图像,或者至少这是它应该的:

//Store the binary image into the database
                $tmp_img = $this->image['tmp_name'];
                $sql = "INSERT INTO ImageStore(ImageId,Image)               
                VALUES('$this->image_id','file_get_contents($tmp_image)')";
                mysql_query($sql); 

如果我打印file_get_contents($tmp_image)的值,那么屏幕上有大量的数据。但是这个值不会存储在数据库中,这就是我面临的问题。


答案 1

问题

$sql = "INSERT INTO ImageStore(ImageId,Image)
        VALUES('$this->image_id','file_get_contents($tmp_image)')";

这将在 PHP 中创建一个名为 的字符串。暂时忘记MySQL,因为您尚未执行任何查询。你只是在构建一个字符串。$sql

PHP的魔力意味着你可以在双引号写一个变量名称——比如说,变量,并且变量仍然会神奇地扩展。$this->image_id

此功能称为“变量插值”,不会对函数调用发生。因此,您在此处要做的就是将字符串写入数据库。"file_get_contents($tmp_image)"


解决方案 (1)

因此,要连接调用的结果,您必须跳出字符串并显式执行操作:file_get_contents($tmp_image)

$sql = "INSERT INTO ImageStore(ImageId,Image)
        VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";

(您甚至可以仅从语法中看到,突出显示了它是如何工作的。


解决方案 (2)

现在你遇到的问题是,如果二进制数据包含任何 ,你的查询是无效的。因此,您应该运行它以对其进行清理以进行查询操作:'mysql_escape_string

$sql = "INSERT INTO ImageStore(ImageId,Image)
        VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";

解决方案 (3)

现在你有一个非常大的字符串,你的数据库变得庞大。

不要将图像存储在数据库中,在那里您可以提供帮助。


答案 2

为了扩展Tomalak的评论,你不能在引号内运行函数。

尝试:

$sql = "INSERT INTO ImageStore(ImageId,Image)               
        VALUES('{$this->image_id}','".file_get_contents($tmp_image)."')";

推荐