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 operat开发者_Go百科ions 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
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.
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).
I would discard the original image name, give every image an unique id and store the original name in the db.
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.
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.
精彩评论