Reputation: 38
I have csv file. and i have already uploaded now i want put its data into my database in cakephp 2.7.5
csv file contain field name exactly same as employee table field name my question is how to put data in employee table here function code
public function import_csv(){
$this->loadModel('Csvimport');
if ($this->request->is('post', 'put')) {
$this->request->data['Csvimport']['created_user_id'] = $this->Auth->user('id');
$this->request->data['Csvimport']['modified_user_id'] = $this->Auth->user('id');
if (!empty($this->request->data)) {
$file = $this->request->data['Csvimport']['file_name'];
$name = explode(".", $file['name']);
//echo "before:".$file['name'][$i];
$name = uniqid().".".$name[1];
//echo "after:".$name;
$ext = substr(strtolower(strrchr($name, '.')), 1); //get the extension
$arr_ext = array('csv'); //set allowed extensions
//only process if the extension is valid
if ($file['size'] < 1000000) {
if(in_array($ext, $arr_ext)){
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/attachments/csvimports/' . $name);
//prepare the filename for database entry
$this->request->data['Csvimport']['file_name'] = $name;
$this->request->data['Csvimport']['file_type'] = $file['type'];
$this->request->data['Csvimport']['file_size'] = $file['size'];
}else{
$message = 'Your File should be in given formats only.';
$this->set('message',$message);
$this->Session->setFlash($message, 'error_flesh', array(), 'error');
$this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv'));
}
}else{
$message = 'Your File should be Upto 1MB only.';
$this->set('message',$message);
$this->Session->setFlash($message, 'error_flesh', array(), 'error');
$this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv'));
}
}
$this->Csvimport->id = $id;
if ($this->Csvimport->save($this->request->data)){
$message = 'The Csv File has been Uploaded';
$this->set('message',$message);
$this->Session->setFlash($message, 'success_flesh', array(), 'successfully');
$this->redirect(array('controller' => 'csvimports' , 'action' => 'import_csv'));
} else {
$message = 'The Csv File could not be Uploaded. Please, try again.';
$this->set('message',$message);
$this->Session->setFlash($message, 'error_flesh', array(), 'error');
}
}
}
Upvotes: 0
Views: 853
Reputation: 756
If you need to loop over every row of data before importing it, consider using
$this->Csvimport->create()
$this->Csvimport->save(['fieldName'=>$data1, 'fieldName'=>$data2, ... ]);
If you don't need that, then use saveAll on the whole array once you have it as such. here is cakes documentation:
http://book.cakephp.org/2.0/en/models/saving-your-data.html
Upvotes: 1