0

I have an old user site that we are currently updating. The site's users have previously uploaded profile pics that are stored in a directory. I am now wanting to keep these profile images in the database, (easy to backup all data) but am having trouble working out how to do it.

There are a lot of tutorials talking about do ing this from files that have just been uploaded and using the tmp name etc, but how can I re-create with files that have already been uploaded?

I have looked into $data = file_get_contents($filename); Which seems to create a binary file, but doesn't seem to save in database with:

mysql_query("UPDATE profiles SET company_logo = mysql_real_escape_string('".$data."') WHERE id = 1 ") or die(mysql_error());

*UPDATE* So after looking into this some more, I think I will go with the majority and save the images as they already are... in folders..

jimbo
  • 1,018
  • 4
  • 18
  • 34
  • 2
    Please please please don't do that. The filesystem is an awesome database for files. – Adi Sep 06 '12 at 09:32
  • You really shouldn't store files in the database. There are good reasons why files should stay in the filesystem. Have a look at [this question](http://stackoverflow.com/questions/492549/how-can-i-insert-large-files-in-mysql-db-using-php) – Aleks G Sep 06 '12 at 09:34

1 Answers1

1

It's generally a bad idea to store images in the database.

It is better to store the images in a file and keep a reference in a field or table.

However, if you want to store them, you must store them as BLOB (Binairy Large OBject). On a BLOB field, no character translation is done. When you store them, you must store them exactly as the file contents. So remove the mysql_real_escape string, as it will mess up your binary data.

JvdBerg
  • 21,777
  • 8
  • 38
  • 55
  • Why is it a bad idea to store image in database? I know the loading times might be slightly slower... – jimbo Sep 06 '12 at 09:39
  • 1
    It always difficult not to start a war on db image storage :) Have a look ath this discussion: http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – JvdBerg Sep 06 '12 at 09:49
  • Remove mysql_real_escape_string may be dangerous. Thinks what would happen if you actually have something like `'); drop table x;` in the file? A _much_ better approach would be to use prepared statements and then execute them with the blob data. That way DB server/driver would handle any necessary conversion itself. – Aleks G Sep 06 '12 at 09:55
  • For the blob storage, you have to remove the mysql_real_escape_string, otherwise the binary data will(could) mess up, depending on the contents. I agree, that if you store binary data, one always should use parameter binding. – JvdBerg Sep 06 '12 at 10:06