Cyberomin
Cyberomin

Reputation: 523

Storing Images in a mysql database

what is the best way to uniquely store and image name in a DB, assuming two persons have the same image name, or the same user uploads the same image twice. How can i manage scenerios like this so that when i want perform operations like updating, deleting, i don't end up deleting both images or all. My DB is MySQL.

Edit - Ok, now for some reason i generated a unique time stamp for all the image everything work on localhost, but when i take it online it doesn't work, i cannot delete it, but it works offline well.

Thank you @cybeormin

Upvotes: 1

Views: 771

Answers (5)

Nico Huysamen
Nico Huysamen

Reputation: 10427

Associate an unique key (primary key) with each entry. Something like:

fileId | file_name | file

and set the fileId to be auto incrementing and a primary key. You can then on your "user" table (if you have something like that) simply reference the fileId as a foreign key.

userId | ... | fileId | ...

Then, if you need to delete the file, simply use the fileId to find the one you which to delete.

Upvotes: 0

SW4
SW4

Reputation: 71220

In your mySQL DB, create a table for image uploads, create an ID column set to AUTO_INCREMENT, INT (integer) and make it the PKEY (primary key).

This will mean your ID's are always automatically created and generated when new content is added, and are always unique regardless of whether the same image is added any number of times.

Additional fields can then trap the other image information (filename, 'given' name, filesize, filetype and a BLOB field for the image itself), you can then also even add a psuedo ID which you make up based on any combination of factors..should you see fit.

Upvotes: 0

Simon
Simon

Reputation: 4585

I would discard the original image name, give every image an unique id and store the original name in the db.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799240

Put a refcount on the images. When you want to delete the image just decrement the refcount instead. When the refcount hits 0, you delete the row for real (or have a cron job delete it).

Upvotes: 0

Scott
Scott

Reputation: 3977

In any table I would recomend an ID column that that is Auto Increment and set to the Primary Field. That way all rows are unique despite a user have two images of the same name.

Upvotes: 1

Related Questions