Home >Backend Development >PHP Tutorial >How to Properly Store Images (Blobs) in MySQL Using PHP?
When attempting to store an image in a MySQL database, you may encounter issues if your query fails to insert the image. This article will provide solutions to this problem.
Problem:
In the following query, file_get_contents($tmp_image) is treated as a string rather than a function call:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','file_get_contents($tmp_image)')";
Solution 1:
Jump out of the string and perform explicit concatenation:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";
Solution 2:
Escape binary data to prevent invalid queries:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";
Solution 3:
Minimize database size by storing images in a file system or by using cloud storage services.
The above is the detailed content of How to Properly Store Images (Blobs) in MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!