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..

2
  • 2
    Please please please don't do that. The filesystem is an awesome database for files. Commented Sep 6, 2012 at 9: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 Commented Sep 6, 2012 at 9:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why is it a bad idea to store image in database? I know the loading times might be slightly slower...
It always difficult not to start a war on db image storage :) Have a look ath this discussion: stackoverflow.com/questions/3748/…
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.