且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-30 16:55:31

问题

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

这将在PHP中创建一个名为$sql的字符串.暂时不要使用MySQL,因为您尚未执行任何查询.您只是在构建一个字符串.

This creates a string in PHP named $sql. Forget about MySQL for a minute, because you're not executing any query yet. You're just building a string.

PHP的神奇之处在于,您可以编写一个变量名—.例如$this->image_id inside 中的双引号和变量仍然得到了神奇的扩展.

The magic of PHP means that you can write a variable name — say, $this->image_idinside the double quotes and the variable still gets magically expanded.

此功能称为变量插值",不会在函数调用中出现.因此,您在这里要做的就是将字符串"file_get_contents($tmp_image)"写入数据库.

This functionality, known as "variable interpolation", does not occur for function calls. So, all you're doing here is writing the string "file_get_contents($tmp_image)" into the database.

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

So, to concatenate the result of calling file_get_contents($tmp_image), you have to jump out of the string and do things explicitly:

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

(您甚至可以仅从突出显示其工作原理的语法中看到.)

(You can see even just from the syntax highlighting how this has worked.)

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

Now the problem you have is that if the binary data contains any ', your query is not valid. So you should run it through mysql_escape_string to sanitize it for the query operation:

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


解决方案(3)

现在您有一个 really 大字符串,并且您的数据库越来越庞大.


Solution (3)

Now you have a really big string, and your database is getting bulky.

首选不在数据库中存储图像,您可以在其中提供帮助.

Prefer not storing images in databases, where you can help it.