我有csv文件。我现在已经上传了我想把它的数据放入我的数据库cakephp 2.7.5
csv文件包含与employee表字段名称完全相同的字段名称 我的问题是如何将数据放在员工表中 这里是功能代码
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');
}
}
}
答案 0 :(得分:1)
如果您需要在导入之前遍历每一行数据, 考虑使用
$this->Csvimport->create()
$this->Csvimport->save(['fieldName'=>$data1, 'fieldName'=>$data2, ... ]);
如果您不需要,请在完成后使用整个阵列上的saveAll。 这是糕点文件: