Codeigniter 3 – Upload file and insert data into database!

photo-upload-codeigniter

NOTE: This tutorial requires the basic knowledge of Codeigniter to understand it.

In this post, we are going to see how to upload a file using the Codeigniter 3 framework and save the uploaded file data into the database.

I have used Codeigniter 3.4.1 for this demo. Also, I am going to attach this demo script at the end of the post so you can download and play with the code.

If you want to start from scratch, just go to the Codeigniter website and download the latest version yourself, here is the link: https://codeigniter.com/download

After you download the zip, extract it, and put it inside the htdocs folder (local environment). Then rename it as you wish but if you want to follow step by step rename it to ‘codeigniter3‘. So the folder structure may look something like this c:/xampp/htdocs/codeigniter3

MYSQL PART:

Now go to MySQL or open PHPMyAdmin and create a database name called ‘codeigniter3‘ and then create a table called ‘pictures’. I am attaching the table structure here:

CREATE TABLE `pictures` (
  `pic_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `pic_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `pic_desc` text COLLATE utf8_unicode_ci NOT NULL,
  `pic_file` varchar(255) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

MySQL part is over. No need to go to the database again.

HTACCESS:

Create a .htaccess file inside codeigniter3 folder and put the following code in it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

This removes the index.php from the URL

CODEIGNITER CONFIGURATIONS:

1) First, open the database.php file inside /codigniter3/application/config/database.php and change the MySQL hostname, username and password as per your database server configuration:

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',//change this as per your server
	'username' => 'root',//change this as per your server
	'password' => '', //change this as per your server
	'database' => 'codeigniter3',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);

2) Then, open config.php file inside /codigniter3/application/config/config.php and set the $config[‘base_url’] to $config[‘base_url’] = ‘https://localhost/codeigniter3/’;

3) And finally our demo requires some libraries and helpers should be auto-loaded. Especially database library, form and url helpers. So open autoload.php  inside /codigniter3/application/config/autoload.php and then find the below variable $autoload[‘libraries’] and $autoload[‘helpers’] and change it as shown here:

.
.
$autoload['libraries'] = array('database');
.
.
$autoload['helper'] = array('url','form');

Now everything is set. Let’s create our Models, Views, and Controllers.

MODELS:

We are going to create only one model for this demo – Pic_model.php.

Code for Pic_model.php (PATH:  /codeigniter3/application/models/)

<?php 

class Pic_model extends CI_Model{
    
    //fetch all pictures from db
    function get_all_pics(){
        $all_pics = $this->db->get('pictures');
        return $all_pics->result();
    }

    //save picture data to db
    function store_pic_data($data){
        $insert_data['pic_title'] = $data['pic_title'];
        $insert_data['pic_desc'] = $data['pic_desc'];
        $insert_data['pic_file'] = $data['pic_file'];

        $query = $this->db->insert('pictures', $insert_data);
    }
    
}

The above model has only two functions in it. get_all_pics() which will fetch all the results from the table ‘pictures’ and store_pic_data() will insert the data into the same table ‘pictures’.


CONTROLLERS:

There are two controllers we are going to write for our demo script. Welcome.php and Upload.php

Code for Welcome.php (PATH:  /codeigniter3/application/controllers/):

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	public function index()
	{
		$this->load->model('pic_model');

		$data['picture_list'] = $this->pic_model->get_all_pics();
		
		$this->load->view('header');
		$this->load->view('picture_list', $data);
		$this->load->view('footer');
	}
}

Welcome.php is the default controller which is going to load as soon as you type https://localhost/codeigniter3. This controller fetches the picture list from database ($this->pic_model->get_all_pics())and then loads the data to the picture_list view.


Code for Upload.php (PATH:  /codeigniter3/application/controllers/):

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Upload extends CI_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->model('pic_model');
		$this->load->library('form_validation');
		
		$this->load->view('header');

	}
	
	public function form(){
		$this->load->view('upload_form');
		$this->load->view('footer');
	}
	
	public function file_data(){
		//validate the form data 

		$this->form_validation->set_rules('pic_title', 'Picture Title', 'required');

        if ($this->form_validation->run() == FALSE){
			$this->load->view('upload_form');
		}else{
			
			//get the form values
			$data['pic_title'] = $this->input->post('pic_title', TRUE);
			$data['pic_desc'] = $this->input->post('pic_desc', TRUE);

			//file upload code 
			//set file upload settings 
			$config['upload_path']          = APPPATH. '../assets/uploads/';
			$config['allowed_types']        = 'gif|jpg|png';
			$config['max_size']             = 100;

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

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

				//file is uploaded successfully
				//now get the file uploaded data 
				$upload_data = $this->upload->data();

				//get the uploaded file name
				$data['pic_file'] = $upload_data['file_name'];

				//store pic data to the db
				$this->pic_model->store_pic_data($data);

				redirect('/');
			}
			$this->load->view('footer');
		}
	}
}

Upload.php – This controller validates the form and does the upload job. Just read through the inline comments in the above code to understand it.


VIEWS:

There are four views we have to create for this demo. In that two files are just partials (header.php and footer.php) and the other two files are main files (picture_list.php and upload_form.php)

Code for header.php (PATH:  /codeigniter3/application/views/):

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">

  <h1 style="font-style:italic">Codeigniter 3 - Form &amp; File upload tutorial</h1>
	<hr />


Code for footer.php (PATH:  /codeigniter3/application/views/):

<br /><br />
<p class="footer" style="bottom:0">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>

</div>

</body>
</html>


Code for picture_list.php (PATH:  /codeigniter3/application/views/):

  <h2>List of Pictures</h2>
  <?php if(count($picture_list)){?>
	  <table class="table table-bordered">
		<thead>
		  <tr>
			<th>Title</th>
			<th>Description</th>
			<th>Thumbnail</th>
		  </tr>
		</thead>
		<tbody>
		<?php foreach ($picture_list as $pic): ?>
		  <tr>
			<td><?=$pic->pic_title;?></td>
			<td><?=$pic->pic_desc;?></td>
			<td><a href="<?=base_url().'assets/uploads/'.$pic->pic_file;?>" target="_blank"><img src="<?=base_url().'assets/uploads/'.$pic->pic_file;?>" width="100"></a></td>
		  </tr>
		<?php endforeach ?>
		</tbody>
	  </table>
	  <br />
	  <a href="<?=base_url().'upload/form';?>" class="btn btn-primary">Upload More</a>
  <?php } else { ?>
    <h4>No Pictures have been uploaded!. Click this button to <a href="<?=base_url().'upload/form';?>" class="btn btn-primary">upload</a></h4>            
  <?php } ?>


Code for upload_form.php (PATH:  /codeigniter3/application/views/):

<h3>Upload a picture!</h3>
<hr />

<div style="color:red">
	<?php echo validation_errors(); ?>
  <?php if(isset($error)){print $error;}?>
</div>
<?php echo form_open_multipart('upload/file_data');?>

  <div class="form-group">
    <label for="pic_title">Picture Title*:</label>
    <input type="text" class="form-control" name="pic_title" value="<?= set_value('pic_title'); ?>" id="pic_title">
  </div>
  <div class="form-group">
    <label for="pic_desc">Picture Description:</label>
    <textarea name="pic_desc" class="form-control" id="pic_desc"><?= set_value('pic_desc'); ?></textarea>
  </div>
  <div class="form-group">
    <label for="pic_file">Select Image*:</label>
    <input type="file" name="pic_file" class="form-control"  id="pic_file">
  </div>
  <a href="<?=base_url();?>" class="btn btn-warning">Back</a>
  <button type="submit" class="btn btn-success">Submit</button>
</form>

You can see the live demo of this code or just download the entire script here:

demodownload

12 thoughts on “Codeigniter 3 – Upload file and insert data into database!

  1. When i execute the code , after submission the error is coming “Object Not Found”,
    I am beginner in codeigniter, please help me

Leave a Reply

Theme: Overlay by Kaira
Agurchand