【问题标题】:How to upload multiple files using CI but only save once to database?如何使用 CI 上传多个文件但只保存一次到数据库?
【发布时间】:2017-05-07 14:47:18
【问题描述】:

我是使用 PHP CI 框架的新手。在我的项目中,我有多个上传输入。

<form method="post" action="<?php echo site_url('upload_img/om_telolet_om'); ?>">
<input type="text" id="student_id" name="student_id" />
<input type="text" id="arr_img_student" name="arr_img_student" />

<input class="up_img" type="file" name="image1" /><br />
<input class="up_img" type="file" name="image2" />
<input type="submit" value="submit" />
</form>

然后,我使用 jQuery 填充up_img 的值并将其放入arr_img_student。然后将数据发送到控制器。这是控制器:

//UPLOAD
public function om_telolet_om()
{
    $this->load->helper('url');

    //UPLOAD FILE RULES 
    $config['upload_path']     = './asset/images/uploads/';
    $config['allowed_types']    = 'gif|jpg|jpeg|png';
    $config['max_size']     = '0';
    $config['max_width']        = '1024';
    $config['max_height']   = '768';
    $config['overwrite']        = TRUE;

    $this->load->library('upload', $config);
    $this->upload->initialize($config);

    for($x = 1; $x<=2; $x++){
       $value = "image".$x;

       if ( ! $this->upload->do_upload($value)){
            $data['error'] = $this->upload->display_errors();           
            $this->load->view('f_upload', $data);
       }
       else
       {
             $data['id']       = $this->input->post('student_id');
             $data['img_path'] = $this->input->post('arr_img_student');     

             $this->model_student->insert_student($data);           
       }         
    }           
}

循环上传和循环插入过程的代码。 如何使代码循环上传(检查上传规则)但只保存一次到数据库?如果上传规则匹配,则应保存数据。在我的数据库中,只使用了一个表。 student_idimg_path。我没有更改数据库结构的特权。

【问题讨论】:

  • "student_id 和 img_path。我没有更改数据库结构的权限。"好吧,如果用户可以上传许多文件,这显然需要单独的文件表和用户表。
  • 我无法创建另一个表。这就是为什么我将图像路径存储到字符串分隔的唯一文本
  • 抱歉,这不是在 RDBMS 中存储数据的正确方法
  • 我知道。那么,如果我没有权限创建另一个表,我该怎么办。我必须考虑另一种解决方案。

标签: php mysql codeigniter file-upload


【解决方案1】:
$images = array(); // an array to store uploaded images in

for($x = 1; $x<=2; $x++){
   $value = "image".$x;

   if ( ! $this->upload->do_upload($value)){
        $data['error'] = $this->upload->display_errors();           
        $this->load->view('f_upload', $data);
   }
   else
   {
        $filedata = $this->upload->data();

        // Every time a file is uploaded, 
        // add it to the array for saving later
        $images[] = $filedata['full_path'];
   }         
}     

$data['id']       = $this->input->post('student_id');
$data['img_path'] = json_encode($images); // Encode $images array to string

$this->model_student->insert_student($data);           

稍后在使用表中的数据时,您必须将 img_path 解码回数组:

$student_images = json_decode($data['img_path'], true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多