When needing to store an image in a MySQL database, one may encounter difficulties. Here's the table structure:
mysql> describe ImageStore; +---------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+----------+------+-----+---------+-------+ | ImageId | int(11) | NO | PRI | NULL | | | Image | longblob | NO | | NULL | | +---------+----------+------+-----+---------+-------+ 2 rows in set (0.01 sec)
The following query attempts to insert an image, but fails to store the expected binary data:
$tmp_img = $this->image['tmp_name']; $sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','file_get_contents($tmp_image)')"; mysql_query($sql);
The issue lies in the concatenation of the function call file_get_contents($tmp_image) inside the string. PHP's variable interpolation only works for variables, not function calls. Here are three solutions:
Solution 1: Use explicit concatenation:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";
Solution 2: Sanitize binary data for MySQL query:
$sql = "INSERT INTO ImageStore(ImageId,Image) VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";
Note: Prefer not storing large images in MySQL databases if possible.
The above is the detailed content of How to Properly Insert Image Blobs into MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!