在数据库,codeigniter中上传图像和图像名称时出错

时间:2019-02-21 20:41:47

标签: codeigniter

在Codeigniter中上传图像时出错。文件名noimage保存在数据库中。

//上传图像控制器

      $config['upload_path'] = './assets/Images/profilepictures';
      $config['allowed_types'] = 'gif|jpg|png|jpeg';
      $config['max_size'] = '2048';
      $config['max_width'] = '2000';
      $config['max_height'] = '2000';

      $this->load->library('upload', $config);

      if(!$this->upload->do_upload()){
          $errors = array('error' => $this->upload->display_errors());
          $post_image = 'noimage.jpg';
      } else {
          $data = array('upload_data' => $this->upload->data());
          $post_image = $_FILES['userfile']['name'];
      }

      $this->m_user->profilepicture($post_image);
      if($data['user']->profile_pic==null)
      {
            redirect(base_url().'user/profilepicture/');

      }

模型

    public function profilepicture($post_image){
$userID = $this->session->userdata("user_id");
            $data = array(
            'profile_pic' => $post_image,
            );
      $this->db->where('user_id', $userID);
      $this->db->update('users', $data);
    }

2 个答案:

答案 0 :(得分:0)

您的图像名称未插入数据库中,因为在更新查询中,您没有传递 $ userID 值。

型号更改=>

public function profilepicture($userID,$post_image)  //Pass $userID here from Controller.
{
    $data = array(
        'profile_pic' => $post_image,
    );
    $this->db->where('user_id', $userID);
    $this->db->update('users', $data);
}

控制器中的更改=>

$userID = $data['user']->user_id;  //Add this line.

$this->m_user->profilepicture($userID,$post_image);  //Update here

您的页面被重定向是因为profile_pic始终为 null ,因为它没有在数据库中更新。因此,在数据库中成功插入profile_pic后,您的页面将不会重定向到redirect(base_url().'user/profilepicture/');

答案 1 :(得分:0)

未上传图片时,请尝试重定向回表单,不要将noimage.jpg添加到数据库中

if(!$this->upload->do_upload()){
      $errors = array('error' => $this->upload->display_errors());
      //Redirect to form with error message
  } else {
      //Get image name like this
      $data = $this->upload->data();
      $post_image = $data['file_name'];

      //Call model function only when image successfully uploaded
      $this->m_user->profilepicture($post_image);
  }

仅在成功上传图片后调用模型功能

因此,请删除此条件if($data['user']->profile_pic==null)