2

What is the proper way to upload images into a MySQL database?

Generally, I declare the 'image' field as text and I use move_uploaded_file() function in order to save images on my server.

Is this the correct way to upload images into a database? I will have to upload lot of images, as social networking website might have to, for instance.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Vivek Kumar
  • 1,204
  • 4
  • 15
  • 35
  • Yes it is a good way. Store images on file system and store their names in database – Hanky Panky Oct 12 '13 at 02:22
  • Controversial solution -- conventional wisdom might say to use db for pathnames and store actual images on file server. All comes down to performance and needs though. but take a look at this: http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Neil Neyman Oct 12 '13 at 02:23
  • R u sure you have such a big database? Its definitely not a correct idea to save images imto database.. – Vicky Gonsalves Oct 12 '13 at 02:45
  • 1
    I can't think of a reason you'd want to save images to the database rather than the filesystem. – Joao Oct 12 '13 at 02:46

3 Answers3

3

I think there are two reliable ways to work with images into your database:

1 - Store the file in some folder at your server, then write the filepath in some field in your image table.

2 - Encode your image as base64 with the base64_encode($yourImageData) method. This method will return a string that can be inserted into your table.

  • 2
    The second one in my opinion is better than using BLOB field. And worster than the first one. – Guilherme Soldateli Oct 12 '13 at 02:43
  • Why is it better then using `BLOB` field? – tereško Oct 17 '13 at 01:15
  • I've got some problems with images within blob fields when : 1- Database grows and then i needed to restore backups with 10+ GB of data. 2 - Depending on your database structure, retrieving a dataset with images can slow significantly your queries. (This one i managed with a table only for blob files). If you're sure that your database will not grow so much, blob fields can be a fast solution. Otherwise, having a nice abstraction for file handling solved nicely my problems. Hope it helped ! – Guilherme Soldateli Oct 17 '13 at 02:15
2

Preferably upload the image to server using File handling and PHP image libraries like GD and then store path as string in database. I think that should work.

  • 1
    I do the same thing. I wanted to know is it possible to save images into mysql database instead of saving path of the image. – Vivek Kumar Oct 12 '13 at 02:23
0

As pointed out, it is not a good idea to save the image directly into database compared to save image on filesystem then save path/link to table fields.

but since the question is "upload images into mysql database"

I think you can check http://www.mysqltutorial.org/php-mysql-blob/

http8086
  • 1,306
  • 16
  • 37