Database does not have enough time to save the record

47 Views Asked by At

I am working on a project on CakePHP 2.4.4. And I am facing the following problem: My Vendor Uploading Class calls one function newImage which creates a new image. When I upload more than one image for example five times, this function is being called five time in a row. This function contains code like:

...    
...initializing Uploader class
...
//creating image
$this->Orderimage->create();
    $data = array(
    'order_id' => $order_id,
    'filename' => $filename,
    'date' => date('Y-m-d'),
    'extension' => $result['ext'],
);
$this->Orderimage->save($data);

But here is the place where I meet my problem. When I am trying to upload more than 4 images, which means that I call this function more than 4 times in a row some image are not uploaded and instead of them the previous pictures are uploaded. The reason for this is that these images are getting the same filename. But the filename is given by the last created image+1. Therefore the bug is that the database does not have enough time to save the image, when the next arrives. And this is the reason, that some image overwrite another. How could I fix it ?

2

There are 2 best solutions below

0
Dave On BEST ANSWER

Try setting the filename as something unique instead of just using +1.

For example:

$filename = CakeText::uuid() . '.jpg'; // or try String::uuid()

That way you don't need to worry about accidentally having the same filename.

https://book.cakephp.org/2.0/en/core-utility-libraries/string.html#CakeText::uuid

Side note: if you're uploading a lot of files into a single directory, it's a good idea to put them in nested directories (3 deep is common). For example something like:

$filename = rand(0,99) . DS . rand(0,99) . DS . rand(0,99) . $file;

If you did it this way, it'd be very unlikely you'll have the same filename+number combination in the same folder. Just store the path as well as the filename, and you're good to go. This will keep a single folder from having so many images that it takes forever to view as well.

NOTE: I just wrote this code off the top of my head - I did not verify it for syntax...etc, but it should give you the idea.

0
om1 On

Daves solution should solve your problem but if you insist to user your filename convention, get the last inserted id and create all images in a loop with $lastInsertedId + $counter bevore saving them. Write the hole image array afterwards to your db.

NOTE: You should use this solution only if you have no simultaneous write requests!