Home >Backend Development >PHP Tutorial >How to Safely Insert Image Blobs into MySQL Databases using PHP?
Inserting images into a MySQL database using PHP can be tricky. One common mistake is to directly embed the binary data using file_get_contents(). Doing so results in a string representing the function call being stored instead of the actual image data.
To properly insert the image data, you need to concatenate the result of file_get_contents(). This can be done by jumping out of the string and explicitly appending the value:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";
Binary data may contain special characters that can invalidate the SQL query. To prevent this, escape the data using mysql_escape_string():
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";
Storing large images in a database can lead to performance issues. Consider using a separate file storage system, such as Amazon S3 or a file system, and storing the image path or reference in the database instead.
The above is the detailed content of How to Safely Insert Image Blobs into MySQL Databases using PHP?. For more information, please follow other related articles on the PHP Chinese website!