Search code examples
phpmysqlcakephp-2.0mysql-insert-id

CakePHP 2.0 file upload not working


Hi Im trying to create a file upload system where I am able to upload a file and it will change the filename to the MYSQL ID that has been uploaded onto the table. This is my code...

function add() {
    if (!empty($this->data)) {
        $this->Upload->create();
        if ($this->uploadFile() && $this->Upload->save($this->data)) {
            $this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
            $this->redirect(array('action' => 'add'));
        } else {
            $this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
        }
    }
        }

function uploadFile() {
    $file = $this->request->data['Upload']['file'];
    if ($file['error'] === UPLOAD_ERR_OK) {
        if (move_uploaded_file($file['tmp_name'], APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
            $this->Upload->save($this->data);
            return true;
        }
    }
    return false;
}

However the file is not being uploaded to the directory but the information is being uploaded to the sql tabe.

I don't see why this function $this->Upload->id is not working for the file rename? If I put it in speech marks then it renames the file to "$this->Upload->id.mp4" but I want it to be more like 114.mp4 if thats the field where the information has being saved. Anybody have any ideas?

Thanks in advance


Solution

  • You need to save first. $this->Upload->id is empty in your case.

    For your interest: $this->Upload->create(); clears $this->Upload->id

    See also:

    http://api20.cakephp.org/class/model#method-Modelcreate http://api20.cakephp.org/view_source/model#line-1381