Home > Backend Development > PHP Tutorial > How to Successfully Insert Blobs (Images) into MySQL using PHP?

How to Successfully Insert Blobs (Images) into MySQL using PHP?

Mary-Kate Olsen
Release: 2024-11-28 01:24:09
Original
653 people have browsed it

How to Successfully Insert Blobs (Images) into MySQL using PHP?

Inserting Blobs into MySQL Databases with PHP

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

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

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

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!

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