CodeIgniter - 从多个映像将文件名写入数据库

时间:2012-08-30 05:14:22

标签: codeigniter

我有一个包含两个文件上传字段的上传表单。我正在尝试上传文件,然后将文件名写入数据库中的同一行。除了将文件名写入自己的行之外,我一切正常。我猜这是因为我正在对模型进行两次单独的调用,但我不确定如何在一次调用中执行它,因为它们各自都有自己的“if”语句。

让我的问题清楚。如何将两个上传文件的名称写入数据库中的同一行?

任何想法都会很棒。这是我正在使用的代码。感谢。

查看:

<?php echo form_open_multipart('upload_controller');  ?>
<p>
    <input type="file" name="userfile">
</p>
<p>
    <input type="file" name="userfile1">
</p>
<p><?php echo form_submit('submit', 'Upload them files!') ?></p>
<?php form_close() ?>

控制器:

if (isset($_POST['submit'])) {
    $this->load->library('upload');

    if (!empty($_FILES['userfile']['name'])) {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '100';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';

        $this->upload->initialize($config);

        // Upload file 1
        if ($this->upload->do_upload('userfile')) {
            $img = $this->upload->data();
            $file_name = $img['file_name'];

            $this->load->model('upload_file', 'upload_model');
            $this->upload_model->upload_file1($file_name);
        }
    }

    if (!empty($_FILES['userfile1']['name'])) {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '100';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';

        $this->upload->initialize($config);

        // Upload file 2
        if ($this->upload->do_upload('userfile1')) {
            $img = $this->upload->data();
            $file_name = $img['file_name'];

            $this->load->model('upload_file', 'upload_model');
            $this->upload_model->upload_file2($file_name);
        } else {
            echo $this->upload->display_errors();
        }
    }
} else {
    $this->load->view("upload_form");
}

型号:

public function upload_file1($file_name) {

    $data = array('file1' => $file_name);
    $this->db->insert('images_table', $data);
}

public function upload_file2($file_name) {

    $data = array('file2' => $file_name);
    $this->db->insert('images_table', $data);
}

数据库行:

| id | file1 | file2 |

1 个答案:

答案 0 :(得分:1)

尝试这样(如果你有文件数......在你的情况下它是&#34; 2&#34;)

$this->load->model('upload_file', 'upload_model');
for($i=1;$i<=$numimg;$i++)                       //in your case $numimg = 2;
{
    if($this->upload->do_upload('File'.$i))      //File1,File2 are filenames
    {
       $img_data = $this->upload->data();
       $images[$i] = $img_data['file_name'];         
    }
 }
 $data['Image'] = implode(',',$images);
 $this->upload_model->upload_file($data);

在你的模特:

public function upload_file2($data)
{
    $data = array('file_name' => $data['Image']);
    $this->db->insert('images_table', $data);
}

那就是它。如果你想从数据库使用中恢复它

$images = explode(',',$data->file_name);

它将为您提供一系列图像名称。