milesj / uploader

[Deprecated] A CakePHP plugin for file uploading and validating.
MIT License
193 stars 73 forks source link

Image ID with Auto_increament #112

Closed msahihi closed 11 years ago

msahihi commented 11 years ago

hi dear i found the problem when for catching id i'm use this method

public function nameCallback($name, $file) {    

   $data = $this->find('first', array(

    'order' => array($this->primaryKey => 'DESC'),

    'limit' => 1
))

if ($data) {

    return $data[$this->alias][$this->primaryKey]++;
}

return $name;}

in this method you get last record id and ++, but imagine if your upload for eg 3 photo with id 1 , 2 and 3 and you remove number 3,what is the next id for photo name?!?! if you using Auto increment your next ID should be 4 but your code get 3 because latest exist record is 2. i solve this problem such as below:

public function naming($name, $file) {

$data =$this->query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = $database AND TABLE_NAME = $table;");

if ($data) {

    return $data[0]['TABLES']['AUTO_INCREMENT'];
}

return $nameaut;}

Can you suggest me better way?!!

milesj commented 11 years ago

This is the only other way I know of. http://stackoverflow.com/a/12500309

msahihi commented 11 years ago

Thanks Dear

co8 commented 11 years ago

Hi Miles,

This function will get the existing ID, or get the next auto increment value.

public function getNextAutoIncrement(){  

    //if edit, then ID already exists
    $id = $this->id;

    //if no ID, then get next Auto Increment value
    if(!$id){
        $table = Inflector::tableize($this->name);
        $result = $this->query("SHOW TABLE STATUS LIKE '$table'");
        $id = $result[0]['TABLES']['Auto_increment']; 
    }

    return $id;         
}

then I call it in the behavior

'Uploader.Attachment' => array( 'icon' => array( 'nameCallback' => 'getNextAutoIncrement' ), ) );

I placed it in AppModel to use it as a nameCallback for Uploader in any Model.

I hope this is helpful! enrique