1

我有一个带有两个文件上传字段的上传表单。我正在尝试上传文件,然后将文件名写入数据库中的同一行。除了文件名被写入自己的行之外,我一切正常。我猜这是因为我对模型进行了两次单独的调用,但我不确定如何在一次调用中进行操作,因为它们都有自己的“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 |
4

1 回答 1

1

像这样尝试(如果你有文件数......在你的情况下它是 "2" )

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

它会给你一个图像名称数组。

于 2012-08-30T05:38:01.323 回答