我是使用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。我没有更改数据库结构的特权。

最佳答案

$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);

关于php - 如何使用CI上传多个文件,但只保存一次到数据库?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41275300/

10-13 08:53
查看更多