Search code examples
phpdatabasecakephpcakephp-2.4

Database does not have enough time to save the record


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 ?


Solution

  • 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.