DB, files, and unique names

November 7, 2007

Almost everyone faced the problem of generation of unique filenames to store on server. For user-uploaded images or something like that. There are several ways to generate an unique name for the file and most common one is to use auto-increment key from database table where the image information stored. Probably it is the best way, but…

You know… there are usually the field for filename in that table. Why? I don’t know, but saw this in a lot of projects.

If you don’t see the problem, I’ll explain:

When just got the file and going to insert the row you can’t know what to put into the filename field because you don’t have the ID yet.

The right way to avoid this problem obviously is to not use the filename field at all. You don’t need need it because filename can be generated from ID anytime.

It’s so simple, right? The main question is why I see filename field again and again and again. I don’t know. Do you?