Home > Database > Mysql Tutorial > How to Properly Insert Blobs (Images) into MySQL using PHP?

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

Linda Hamilton
Release: 2024-12-20 09:43:13
Original
470 people have browsed it

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

Insert Blobs in MySql databases with php

When attempting to store an image in a MySQL database, you might encounter an issue. This guide will provide solutions to successfully store your image data.

Issue

<br>$sql = "INSERT INTO ImageStore(ImageId,Image)<br>VALUES('$this->image_id','file_get_contents($tmp_image)')";<br>

This code builds a string in PHP, but the function call file_get_contents($tmp_image) is not evaluated before the string is created. Consequently, the actual binary data is not inserted.

Solution 1

To resolve this, you need to explicitly concatenate the result of the function call:

<br>$sql = "INSERT INTO ImageStore(ImageId,Image)<br>VALUES('$this->image_id','" . file_get_contents($tmp_image) . "')";<br>

Solution 2

Additionally, ensure that any characters in the binary data that might interfere with the query are escaped:

<br>$sql = "INSERT INTO ImageStore(ImageId,Image)<br>VALUES('$this->image_id','" . mysql_escape_string(file_get_contents($tmp_image)) . "')";<br>

Solution 3

Storing large binary data in a database is generally not recommended. It can lead to performance issues and database bloat. Consider using a separate file system to store your images instead.

The above is the detailed content of How to Properly 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