2015-07-04 103 views
0

我是新來的,很高興認識你。codeigniter成功插入數據庫但未能插入上傳的文件

我在codeigniter中遇到了問題。

也許很難說,所以我會告訴我的所有代碼:

我的控制器:

function upload_barang(){ 

    $this->admin_model->login(); 

    $this->admin_model->valid_product(); 

    $config['upload_path'] = './produk/'; 
    $config['allowed_types'] = 'jpg'; 
    $config['max_size'] = '100'; 
    $config['max_width'] = '400'; 
    $config['max_height'] = '400'; 

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

    $data['query'] = $this->db->get('kategori'); 

    if($this->form_validation->run() == FALSE && ! $this->upload->do_upload()) { 

    $data['error'] = $this->upload->display_errors(); 

    $data['success'] = ''; 

    $this->load->view('backoffice/tambahbarang',$data); 

    } else { 

     $upload_data = $this->upload->data(); 

     $data['error'] = ''; 

     $data = array(
     'idkategori' => $this->input->post('idkategori'), 
     'namabarang' => $this->input->post('nbarang'), 
     'image' => $upload_data['file_name'], 
     'status' => 1 
    ); 

    $data_insert = $this->db->insert('barang',$data); 

    if($data_insert == TRUE) { 

     $data['query'] = $this->db->get('kategori'); 

     $query = $this->db->get('barang'); 

     $rows = $query->row(); 

     $data['idbarang'] = $rows->idbarang; 

     $harga = array(
     'idbarang' => $data['idbarang'], 
     'satuan' => $this->input->post('stcbarang'), 
     'harga' => $this->input->post('hbarang') 
    ); 

    $this->db->insert('hargabarang',$harga); 

    $data['success'] = '<b>Barang Telah Ditambahkan</b>'; 

    $this->load->view('backoffice/tambahbarang',$data); 

    } else { 

    $data['success'] = '<b>Barang Gagal Ditambahkan</b>'; 

    $this->load->view('backoffice/tambahbarang',$data); 

    } 

    } 
} 

此代碼成功插入所有的數據到數據庫中,除了在列「形象」,我填'$ upload_data ['file_name']'在我的數據庫中爲空。

我的代碼有什麼問題?

請幫助謝謝

+0

爲什麼你寫的查詢在'controller'這是不好用MVC' – Saty

+0

的'在代碼中刪除此行'$嘗試data ['error'] ='';' – Saty

+0

那只是爲了測試,成功後我會改變它。 – gong

回答

0

您可以使用此格式:

/* 
    * ------- Start Image Upload--------- 
    */ 
    $config['upload_path'] = 'image/product_images/'; 
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['max_size'] = '100'; 
    $config['max_width'] = '400'; 
    $config['max_height'] = '400'; 

    $this->load->library('upload', $config); 
    $this->upload->initialize($config); 
    $error=''; 
    $fdata=array(); 
    if (! $this->upload->do_upload('product_image')) 
    { 
      $error = $this->upload->display_errors(); 
      echo $error; 
      exit(); 
    } 
    else 
    { 
      $fdata = $this->upload->data(); 
      $data['product_image']=$config['upload_path'] .$fdata['file_name']; 
    } 

    /* 
    * --------End Image Upload--------- 
    */ 
    $this->super_admin_model->save_product_info($data); 
+0

嗯謝謝你的回答,但如何form_validation?如果我使用此代碼僅用於上傳圖像,然後將它們保存到數據庫中,那麼表單驗證如何?如何使用表單驗證來組合它們? – gong

相關問題