Question

My web app allows users to upload a bunch of photos simultaneously to the server, and then stores them in a database. When the first photo finishes uploading, it should create a default album based on today's date, and add it to that. But what if photo1 completes, looks for the album, and can't find it so it decides to create it, but before it can, photo2 completes and also can't find it, so then they both try to create the same album, causing one to fail? This would probably be very highly unlikely, but could happen I reckon. Or do most web servers process only one PHP script at a time?

Would this be a valid and good solution?: Instead of photo1 checking if the album exists first, it just tries to create it. If it throws back an error 1062 (duplicate entry), THEN it selects it. Then it shouldn't matter which finishes first if you think about it... I just don't know if catching errors will come as a big performance hit. If I'm uploading 200 photos, then 199 of them will fail the insert query, and then try select. If the other solution works correctly, 199 will succeed and one will miss.

Thoughts?

Was it helpful?

Solution

Combine both

Check if it exists and if it does join

if not try to create one

if that doesnt work start the whole thing again

OTHER TIPS

We have something similar albeit not to do with photos but we simply wait for ALL the items to be sent up before processing them. This means keeping them in a staging area first but solves the other issue.

Why not create the album first, and only display it if it has contents?

So your script logic would look something like:

create album<date>
while more images
    upload next image
    add to album<date>
voila

That way, if they make an album and don't use it, it never displays. You can urn a maintenance script to cleanup all empty albums a day or however long afterwards.

This is what transaction handling and synchronization is all about. If your language (PHP) doesn't provide transaction handling and synchronization, then you can use the database itself to take care of this for you.

I think you got this already - each request should check to make sure that it's attempt to create the album succeeds. If it fails, it can then look to see if some other process/request created it already, and then use that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top