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
Release: 2024-12-26 15:53:09
Original
208 people have browsed it

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)
Copy after login

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); 
Copy after login

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) . "')";
Copy after login

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)) . "')";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template