Codeigniter: how to get the file name

I am new to Codeigniter and I am trying to get the file name of the uploaded image in order to save it to the database. I have two models, homemodel deals with my database, and image_upload_model deals with loading images. Everything works fine, except that I don’t know how to send the image file name to the database.

image_upload_model.php

<?php class Image_upload_model extends CI_Model { var $image_path; //constructor containing the image path function Image_upload_model() { $this->image_path = realpath(APPPATH.'../assets/img'); } //uploading the file function do_upload() { $config = array( 'allowed_types' => 'jpg|jpeg|gif|png', 'upload_path' => $this->image_path ); $this->load->library('upload',$config); $this->upload->do_upload(); } } ?> 

homemodel.php

 <?php class homeModel extends CI_Model { //inserting into the table tenants function addTenants() { $this->load->model('Image_upload_model'); $data = array( 'Fname' => $this->input->post('Fname'), 'Lname' => $this->input->post('Lname'), 'contact' => $this->input->post('contact'), 'email' => $this->input->post('email'), 'location' => $this->input->post('location'), 'img_url' => " "//the filename of the image should go here ); $this->db->insert('tenants', $data); } } ?> 

Controller
homecontroller.php

 <?php class HomeController extends CI_Controller { public function index() { $this->load->helper('form'); $this->load->helper('html'); $this->load->model('homemodel'); $this->load->model('Image_upload_model'); if ($this->input->post('submit') == 'Submit') { $this->homemodel->addTenants(); echo 'inserted'; $this->Image_upload_model->do_upload(); echo 'image uploaded'; } $this->load->view('index.php'); } } ?> 

any help is appreciated, thanks!

+7
source share
3 answers

You can get a file name like this

  $upload_data = $this->upload->data(); $file_name = $upload_data['file_name']; 
+17
source

At a very high level, you need to rebuild your code as follows:

(1) In the HomeController upload the image first ( $this->Image_upload_model->do_upload() , and then update your database ( $this->homemodel->addTenants()

(2) In your upload model, you need to call $this->upload->data() to get an information array containing the name of your file (see the CodeIgniter documentation). Then you need to get this file name and make it available to the HomeController and pass it to the addTenants function.

With this guide, you can change your code accordingly.

+2
source

Easy to get file name with $this->upload->file_name

based on function loading in system/library/upload.php

 public $file_name = ""; public function data() { return array ( 'file_name' => $this->file_name, 'file_type' => $this->file_type, ... ); } 
+2
source

All Articles