I am working on a CMS in Codeigniter and it has the usual fields like title, post content, etc (the page is similar to WordPress in this way).
I have an image uploader on the page that saves the image via ajax to a MySQL table with basic fields such as image_id, path, size.
There is another table that stores the relationship between an item and an image that requires both an item_id and an image_id.
The problem I have is that the item_id is not known until the page is created/saved. So if a user goes to the Create Post page and uploads an image from there, I can’t add the relationship since I don’t have an item_id yet.
Some things I am considering:
-
Every time someone goes to the Create Post page, it automatically creates a blank post in the MySQL table with just the item_id and storing it in a hidden field. The problem I have with this is the database could get filled with a lot of empty posts if a person just clicks Create Post but never fills it out.
-
Saving the images in the images table, but also save an array of all of their ids for when the Create button is clicked. When that button is click, then add the image relationships.
-
Hide the image uploader until the post title is filled out, which triggers a page save
WordPress seems to have solved this but I’m not sure what it does?
Anyone have any better suggestions?
I would say to structure your images table so that it doesn’t require a reference to a specific post. Put image-post relationships in a separate table. On your “compose post” screen, have the image uploader return the ID of the newly-inserted image, and when you submit the post, add the new post ID and the image ID to the table for image-post relationships. This also gives you more flexibility to do things like link to one image in multiple posts.
— edit: upon re-reading, it sounds like this is already how you’re storing them. If so, then there shouldn’t be a problem. Just add the image-post relationship at the time the post is submitted. If you’re worried about orphaned images, see below. —
You’re right that this could lead to orphan images, if someone uploads an image and then closes the window without making a post. I wouldn’t worry about the images table “filling up,” though. MySQL tables can have millions of rows and still perform well.
If you’re concerned about collecting unused image files, you could have a periodic maintenance job that removes image files (and the associated table entries) if the upload date is older than, say, 1 week, and the image isn’t associated with any posts.