Insert Blobs in MySql databases with php

Problem

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

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.

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.

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.


Solution (1)

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.)


Solution (2)

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)) . "')";

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.

Leave a Comment