php - 如何使用CI上传多个文件但只保存一次到数据库?

标签 php mysql codeigniter file-upload

我是 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 中。然后数据被发送到 Controller 。这是 Controller :

//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/

相关文章:

PHP:如何确定浏览器是否支持 PHP 中的 javascript?

javascript - 如何使用 javascript 迭代 php 中的 JSON 编码对象

mysql - Yii2:带 CASE 的 OrderBy(订购手册)

mysql - 如何用value+rowID替换表中的所有字段?

PHP:每个数据库项目的唯一页面或带有 _GET 的单个 php 页面?

php - 应用程序在浏览器中超时但在命令行中没有

php - 使用 PHP 将 Backbone JSON 对象保存到 MySQL 表

php - 有两个同名 HTTP GET 参数时的行为

php - 将具有多个字段的数组传递给 codeigniter 中的 View

mysql - Codeigniter 显示错误 : No database selected