无法将变量从控制器传递到模型以处理codeigniter中的多个上载字段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法将变量从控制器传递到模型以处理codeigniter中的多个上载字段相关的知识,希望对你有一定的参考价值。
我在表单中有三个文件输入(每个都有不同的名称:self_pic,passport_pic和sic_pic)。在处理输入的控制器中,我为每个不同的变量分配了上传图像的三个名称,并将变量传递给我已经在模型中定义的函数,这样我就可以在db中保存包含上传图像名称的变量。它适用于两个变量,而不适用于一个变量。我不断得到变量未定义的错误。
这是我在控制器中的代码
$config['upload_path'] = './asset/image/participant_img';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('self_pic')){
$errors = array('error' => $this->upload->display_errors());
$this->load->view('reg_participant', $errors);
} else {
$data = array('upload_data' => $this->upload->data());
$self_pic = $_FILES['self_pic']['name'];
}
if(!$this->upload->do_upload('passport_pic')){
$errors = array('error' => $this->upload->display_errors());
$this->load->view('reg_participant', $errors);
} else {
$data = array('upload_data' => $this->upload->data());
$passport_pic = $_FILES['passport_pic']['name'];
}
if(!$this->upload->do_upload('sic_pic')){
$errors = array('error' => $this->upload->display_errors());
$this->load->view('reg_participant', $errors);
} else {
$data = array('upload_data' => $this->upload->data());
$sic_pic = $_FILES['sic_pic']['name'];
}
$pictures = array ('self_pic' => $self_pic, 'passport_pic' => $passport_pic, 'sic_pic' => $sic_pic);
$this->reg_model->simpan($pictures);
redirect('/registrations_participant', 'refresh');
错误:
而且我觉得写一堆if是脏的,我试着把它们写成循环,但我找不到怎么做。任何的想法?或任何建议如何正确地写它们。谢谢!
答案
我的猜测是该字段为空,因为文件太大(因此没有上传),上传字段名称不正确,或者发生错误并且变量永远不会被设置(您在重定向时看不到)。尝试以下代码(还集成了foreach并删除所有错误的文件以防止孤立)。
$config['upload_path'] = './asset/image/participant_img';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
$upload_fields = array('self_pic', 'sic_pic', 'passport_pic');
$uploaded_files = array();
$error_flag = false;
foreach ($upload_fields as $field_name) {
if (!$this->upload->do_upload($field_name)) {
$errors = array('error' => $this->upload->display_errors());
// delete files on failure as when the user reuploads to fix
// whatever error occurs we don't have duplicates!
if (count($uploaded_files) > 0) {
foreach ($uploaded_files as $file) {
@unlink($file);
}
}
$error_flag = true;
$this->load->view('reg_participant', $errors);
break; // stop everything...
} else {
$uploaded_files[] = $this->upload->data('full_path');
$data[$field_name] = $this->upload->data('file_name');
}
}
// an error occured, don't redirect as then we won't see our error message
// from above view
if (!$error_flag) {
$this->reg_model->simpan($data);
redirect('/registrations_participant', 'refresh');
}
以上是关于无法将变量从控制器传递到模型以处理codeigniter中的多个上载字段的主要内容,如果未能解决你的问题,请参考以下文章
将 managedobject 从 uitableview 传递到文本字段以在核心数据模型中进行编辑
PHP MVC 最佳实践 - 将 Session 变量从控制器传递给模型类或直接在模型中访问