Home >Database >Mysql Tutorial >How to Properly Insert Blobs (Images) into MySQL using PHP?
When attempting to store an image in a MySQL database, you might encounter an issue. This guide will provide solutions to successfully store your image data.
<br>$sql = "INSERT INTO ImageStore(ImageId,Image)<br>VALUES('$this->image_id','file_get_contents($tmp_image)')";<br>
This code builds a string in PHP, but the function call file_get_contents($tmp_image) is not evaluated before the string is created. Consequently, the actual binary data is not inserted.
To resolve this, you need to explicitly concatenate the result of the function call:
<br>$sql = "INSERT INTO ImageStore(ImageId,Image)<br>VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";<br>
Additionally, ensure that any characters in the binary data that might interfere with the query are escaped:
<br>$sql = "INSERT INTO ImageStore(ImageId,Image)<br>VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";<br>
Storing large binary data in a database is generally not recommended. It can lead to performance issues and database bloat. Consider using a separate file system to store your images instead.
The above is the detailed content of How to Properly Insert Blobs (Images) into MySQL using PHP?. For more information, please follow other related articles on the PHP Chinese website!