How to store path image users into a database: Cod

2019-07-12 23:35发布

I am trying to upload the paths of the pictures for different users into at database. I am quite new on codeigniter and I read a lot of tutorials, but I am sill struggling. This is my controller but I don't even know how to link the image with the user session.

Here is my code:

function do_upload()

{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '100';
$config['max_width']  = '1024';
$config['max_height']  = '768';
$config['overwrite'] = false;

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

  if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());

$this->load->view('upload_form', $error);
}else

{    
$data = $this->upload->data();
$file_array = $this->upload->data('file_name');
$profile['profile_picture'] = $file_array['file_name'];
$this->db->where('username', $this->input->post('username'));
$this->db->update('users', $profile);
$this->load->view('upload_success', $data);

   }

}

My database has a table called users and 'profile_picture' is the field for the path. When I upload an image, I just get all my users fields filled with the same file name.

2条回答
该账号已被封号
2楼-- · 2019-07-13 00:02

If your use has an ID, just do imagePath = /upload/avatar/'.$userID.'.jpg' or use a random filename and store it as a new field

查看更多
▲ chillily
3楼-- · 2019-07-13 00:19

thanks for the tips guys I solved in this way:

  function do_upload(){

    if($this->session->userdata('is_logged_in'))
    {
     $id = $this->session->userdata('id');
     $config['upload_path'] = './uploads/';
     $config['allowed_types'] = 'gif|jpg|jpeg|png';
     $config['max_size']    = '100';
     $config['max_width']  = '1024';
     $config['max_height']  = '768';
     $config['overwrite'] = false;

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

     if ( ! $this->upload->do_upload())
     {
      $error = array('error' => $this->upload->display_errors());
      $this->load->view("site_header");
      $this->load->view("site_nav");
      $this->load->view('upload_form', $error);
      }else{    

      $data = $this->upload->data();
      $file_array = $this->upload->data('file_name');
      $profile['profile_picture'] = $file_array['file_name'];
      $this->db->where('id', $id);
      $this->db->update('users', $profile);
      $this->load->view('upload_success', $data);
      }
     }else{
      $this->load->view("site_header");
      $this->load->view("site_nav");
      $this->load->view("login_view");
      $this->load->view("site_footer");
      }   
   }
查看更多
登录 后发表回答