dgnin
dgnin

Reputation: 1597

Conventions and checking file existance vs database storing

I'm building the database structure for a portal and I have some doubts related to elements that I decided aren't going to be stored in the database, typically media and specifically images.

Suppose that we have contents and every content could have a main image. Also, there is a slideshow with featured contents that need big images from the contents. An intuitive idea is leave the DB without this task and store the images with a name convention. Then, in the code (php), I could check if the file exists and then act as desired (asking to upload the image for the slideshow, showing a default image or a map instead of the needed main image...). The other extreme is storing the filename in the database, and other option is use the file name convention but store in the database a boolean instead of checking for the existence in the code.

I'm interested on the subjective perspective, but I would really like to know if there are best practices for this situation based on technical and objective reasons, or simply for practical reasons...

Upvotes: 1

Views: 60

Answers (2)

JvdBerg
JvdBerg

Reputation: 21856

I do not store images in the database. Instead I store them in a separate folder on disk and maintain a table with name, size, mimetype etc.

My practical reasons for not storing them in the database:

  • I use mysqldump and then a editor if I want to make changes in the db structure. That is easier without all the binary data inside the dump.
  • My database server runs on a fast 128GB SSD SATA 600 disk for performance. The space is limited. The images folder is mounted from a NAS storage, that is 12TB in size.
  • When a browser needs a images, it is not loaded with the html, but in a separate request. When delivering html there is no need that the image comes from a lighting fast storage device.

Upvotes: 0

MrCode
MrCode

Reputation: 64536

Store the image filename in the database with each content record. This is the most flexible option because you can easily change the selected image by updating the database record.

Suppose you add some sort of backend/admin area to manage the content. To change the content's main image you can show a dropdown of files in the images folder (and a file upload option) and easily update the record to the chosen image.

If you want a slideshow of content images, you can simply select the image filenames from the table and output <img /> tags pointing to the images.

If you do it without the database, by using a naming convention e.g. content-image-{contentId}.jpg then to change the image you would need to be renaming/deleting files and you would need to cater for different image file extensions.

Upvotes: 1

Related Questions