图像未上传到数据库codeigniter

时间:2016-05-10 07:42:24

标签: php codeigniter

我正在尝试在表单中上传图片。表格中的所有数据都可以存储到数据库中接受图像。并且图像也不会插入upload_path。我想在用户填写所有表单信息并上传图像时,用户点击提交按钮和所有数据,包括图像存储到数据库中。我的代码有什么问题?谢谢。

// view.php

<?php echo form_open_multipart('writereview/create');?>
<label for="sitename"><span>Sitename <span class="required">*</span></span><input type="text" class="input-field" name="sitename" value="" /></label>
<input type="file" name="images"  size="20" /> <br />
<label><span>&nbsp;</span><input type="submit" value="Submit" /></label>

//控制器

public function create() //insert data
{
    $data['title'] = 'Write Review'; // Capitalize the first letter 
    $this->load->helper(array('html', 'url', 'form'));

    $this->config_model->writereview();

    $this->load->view('templates/header', $data);
    $this->load->view('writereview/writereview');
    $this->load->view('templates/footer');
}

//模型

public function writereview()
{
    $this->load->helper('url');

    $type = explode('.', $_FILES["pic"]["name"]);
    $type = strtolower($type[count($type)-1]);
    $url = "./assets/images/".uniqid(rand()).'.'.$type;
    if(in_array($type, array("jpg", "jpeg", "gif", "png")))
        if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
            if(move_uploaded_file($_FILES["pic"]["tmp_name"],$url))
                return $url;


    $data = array(
        'sitename' => $this->input->post('sitename'),
        'images'=>$this->input->post('images')
    );
    return $this->db->insert('review', $data);
}

1 个答案:

答案 0 :(得分:0)

更改插入数据数组

$data = array(
        'sitename' => $this->input->post('sitename'),
        'images'=>$uploaded_file_name
    );

也会更改$_FILES["pic"]["name"] to $_FILES["images"]["name"]

没有名为 images 的帖子键,因为输入类型是文件...

以下是您的示例的完整代码...

        $image_name ='';
        if (isset($_FILES['images']['tmp_name']) && $_FILES['images']['tmp_name'] != '') 
        {
          $config['upload_path'] = 'assets/images/';
          $config['allowed_types'] = 'gif|jpg|png|jpeg';
          $config['max_size'] = '20000'; // change it to your max file size
          $this->load->library('upload', $config);
          $this->upload->initialize($config);
          if (!$this->upload->do_upload('images')) {//if upload error
            print_r($this->upload->display_errors());//print error
          }else{
            $data = $this->upload->data();
            $image_name = $data['file_name'];
          }
        }
        $data = array(
           'sitename' => $this->input->post('sitename'),
           'images'=>$image_name
        );
        return $this->db->insert('review', $data);