Problem:
Attempting to store an image in a MySQL database, but the insert is unsuccessful. The database table has two columns: ImageId (int) and Image (longblob). The PHP code uses file_get_contents() to retrieve the image data and inserts it into the Image column using the following SQL query:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','file_get_contents($tmp_image)')";
However, the image data is not stored in the database.
Solution:
The issue lies in the way the PHP code constructs the SQL query. The file_get_contents() function call is included within single quotes in the query string, which means that the actual image data is not being inserted. To resolve this, the variable interpolation feature of PHP should be used:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";
Additionally, to ensure that the binary data does not contain any characters that could break the SQL query, it's recommended to sanitize the data using the mysql_escape_string() function:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . mysql_real_escape_string(file_get_contents($tmp_image)) . "')";
Additional Considerations:
Storing large binary data in databases can lead to performance issues. Consider using a separate storage medium, such as a file system or a cloud storage service, for images and other large objects.
The above is the detailed content of How to Successfully Insert Blobs (Images) into MySQL using PHP?. For more information, please follow other related articles on the PHP Chinese website!