Kaiden Rogers Kaiden Rogers - 1 year ago 81
MySQL Question

There's got to be a better way to store and retrieve images from a database, Right?

I've been following multiple tutorials on uploading and retrieving images using MySQL and PHP, and they all seem to be using the same technique; upload the image as normal (no problem there) and then create another document and use a PHP script to select the image from the database then change the 'content-type' to image/jpeg, then display said document in an iframe.

That's fine and dandy; if I wanted to display one single image, and I was fine with it being in an iframe. However, I'm developing a CMS(like) system where the end user will be changing many styled images on a particular page and that technique doesn't quite work, as it appears to only work for single image.

I'm not looking to upload the files to a folder, then store the path in the database either. I'd like to store the image itself in the database.

I know this is a broad question and I definitely don't expect anyone to give me a step by step tutorial. But if you could direct me to one that would be great.

Thanks in advance.


The page used to display the image in the way you outline the tutorials show, with retrieval and then a header output is a way that sets the PHP image-calling file to act as an image file .

So you can have

<img src='phpimagefile.php?id=imgreference' alt'my image'>

for example.

If you want to display multiple images like this then you can simply roll the above HTML code into a foreach or similar loop on another page.

foreach ($imagesSet as $image){
    print "<img src='phpimagefile.php?id=".$image['id']."' alt'my image'>\n";


You can get really smart and with some mod_rewrite you can actually store images with filepath names such as :

<img src='/images/45757/goldenShower.jpg' alt='My Image'> 

And the mod_rewrite will reorganise this to be able to find the image of:

<img src='/images/phpimagefile.php?id=45757' alt'my image'>


Storing the images directly in the database is cumbersome and does not solve your (apparent) problem of retrieval.

If you can clarify why being in the database is better for the image than a image output file as I describe above, this will probably show more people (judging from the comments) exactly what your current issue is.

Some Notes:

  • Don't use iframes. Use the HTML img tag as I example above.
  • We can't direct you to any tutorial until we actually understand what you're trying to gain.
  • Even if you upload the files to a database table, you are still going to need to store a reference to that table/row in order to reference the correct image, so imageId = 'files/image/goldenShower.jpg' is just another reference in the Database like imageId = 4365 would be.