Home >Database >Mysql Tutorial >How to Properly Insert Image Blobs into MySQL Using PHP?

How to Properly Insert Image Blobs into MySQL Using PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 15:53:09270browse

How to Properly Insert Image Blobs into MySQL Using PHP?

Inserting Blobs into MySQL Databases with PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn