I'm coding a php script to get an uploaded picture, move it in a folder (let's say "/img") renaming it with a unique name, create a thumbnail with the same name in a subfolder ("/img/small"), and insert a record for the picture in my database where the picture's name is the primary key.
Basically I'm obtaining the unique name from the database itself, after an INSERT INTO, with mysql_insert_id. This means that I'm moving the picture and creating the thumbnails after the database insertion, so if something goes wrong (e.g.: invalid image format, not enough space, etc.) I should perform a "DELETE" from the database, pseudocode:
perform "INSERT INTO ..."
name = inserted_id if (!move_file(temp, "/img/" + name)) perform "DELETE WHERE id = name" if (!create_thumbnail(temp, "/img/small" + name)) perform "DELETE WHERE id = name"
I'd like to know if some of you faced the same problem and came out with a more开发者_Python百科 rational and elegant solution.
Use transactions instead. The basic procedure would be:
- start a transaction
- insert a skeleton image record into the db. Enough to create a record, but not enough that it would show the image as available to the rest of your system
- retrieve the ID of the new record
- do the image processing (resizing, renaming, moving, etc...)
- Update the database record with anything else you need to store (file sizes, resolution, availability, etc...)
- if everything went ok, commit the transaction, otherwise roll back.
精彩评论