How to Upload Image in Codeigniter with database example

calendar_month 04 May 2022 | Codeigniter


In this tutorial, you will learn how to upload image in Codeigniter with database example.

Image uploading is one of the most important functionalities of any back-end project because many images are required on a website, such as product images, category images, profile images, etc. We can upload these images to the Codeigniter website using CodeIgniter's image upload functionality.

Let's do a Codeigniter image upload example by following the steps below.

Step 1: Download and Setup Codeigniter 3

The first step is to download Codeigniter 3 and extract the zip file to the root directory of your local server then set Base URL and autoload libraries and helpers.

Download Codeigniter 3 from the following URL

https://codeigniter.com/download

Step 2: Create Database and Configuration

So, in this step, we will create a new database with the name “blog_website” and add a new table with the name “posts” in the database.

You can create a database table using the following SQL query.

CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `image` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After that, we need to do the database configuration.

application/config/database.php

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'blog_website',
	'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
);

Step 3: Add Route

In this step we need to add some routes in the routes file, so open these files and paste the following code.

application/config/routes.php

$route['default_controller'] = 'ImageUpload';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['image-upload'] = 'ImageUpload';
$route['image-upload/post']['get'] = "ImageUpload/create";
$route['image-upload/post']['post'] = "ImageUpload/store";

 

Step 4: Create Controller

In this step, we need to create an "ImageUpload" controller and its functions so, create and paste the following code into this file.

application/controllers/ImageUpload.php

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

/**
 *  ImageUpload Controller
 */
class ImageUpload extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->load->model('crud');
	}

	public function index()
	{
		$data['data'] = $this->crud->get_records('posts');
		$this->load->view('post/list', $data);
	}


	public function create()
	{
		$this->load->view('post/create');
	}


	public function store()
	{

		$config = array(
			'upload_path' => "./uploads/",
			'allowed_types' => "jpg|png|jpeg|gif",
			'max_size' => "1024000", // file size , here it is 1 MB(1024 Kb)
		);
		$this->load->library('upload', $config);

		if ($this->upload->do_upload('image')) {

			$data['image'] = $this->upload->data('file_name');
			$this->crud->insert('posts', $data);
			$this->session->set_flashdata('message', '<div class="alert alert-success">Record has been saved successfully.</div>');			
		}else{
			$error = array('error' => $this->upload->display_errors());
			$this->session->set_flashdata('message', '<div class="alert alert-danger">'.implode("",$error).'</div>');
		}

		redirect(base_url());
	}





}

Step 5: Create Model

In this step, we need to create a Crud model and paste the following code into this file.

application/models/Crud.php

<?php

/**
 * Crud Model
 */
class Crud extends CI_Model
{

	public function insert($table, $data)
	{
		$result = $this->db->insert($table, $data);
		return $result;
	}


	public function get_records($table)
	{
		$result = $this->db->get($table)->result();
		return $result;
	}
	
}

Step 6: Create View

In this step, we need to create view files to design the web page, so let's create and make the following changes to your files

application/views/post/create.php

<!doctype html>
<html lang="en">

<head>
  <?php $this->load->view('includes/header'); ?>
  <title>Add New Image</title>
</head>

<body>

  <div class="container">
    <div class="row">

      <div class="col-lg-12 my-5">
        <h2 class="text-center mb-3">Codeigniter 3 Image Upload Application</h2>
      </div>

      <div class="col-lg-12">

        <div class="d-flex justify-content-between ">
          <h4>Add New Image</h4>
          <a class="btn btn-warning" href="<?php echo base_url(); ?>"> <i class="fas fa-angle-left"></i> Back</a>
        </div>

        <form method="post" enctype="multipart/form-data">

          <div class="form-group">
            <label>Select Image</label>
            <input class="form-control" type="file" name="image" required>
          </div>

          <div class="form-group">
            <button type="submit" class="btn btn-success"> <i class="fas fa-check"></i> Submit </button>
          </div>

        </form>


      </div>
    </div>
  </div>



  <?php $this->load->view('includes/footer'); ?>

</body>

</html>

application/views/post/list.php

<!doctype html>
<html lang="en">

<head>
  <?php $this->load->view('includes/header'); ?>
  <title>Codeigniter 3 Image Upload Application</title>
</head>

<body>

  <div class="container">
    <div class="row">

      <div class="col-lg-12 my-5">
        <h2 class="text-center mb-3">Codeigniter 3 Image Upload Application</h2>
      </div>

      <div class="col-lg-12">

        <?php echo $this->session->flashdata('message'); ?>

        <div class="d-flex justify-content-between mb-3">
          <h4>Image Listing</h4>
          <a href="<?= base_url('image-upload/post') ?>" class="btn btn-success"> <i class="fas fa-plus"></i> Add New Image</a>
        </div>

        <table class="table table-bordered table-default">

          <thead class="thead-light">
            <tr>
              <th width="30%">S No.</th>
              <th width="70%">Image</th>
            </tr>
          </thead>

          <tbody>

            <?php $i = 1; foreach ($data as $post) { ?>

              <tr>
                <td><?php echo $i; ?></td>
                <td> <img class="img-fluid" src="<?= base_url('uploads/'.$post->image); ?>" style="width: 150px;"> </td>
              </tr>

            <?php $i++; } ?>

          </tbody>

        </table>

      </div>
    </div>
  </div>



  <?php $this->load->view('includes/footer'); ?>

</body>

</html>

application\views\includes\header.php

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">

application\views\includes\footer.php

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

Step 7: Folder Creation

In this step, we need to create a folder in the root directory of the project, all uploaded images will be stored in this folder.

So, create a folder named "uploads" in the root directory.

Congratulations friend, your CodeIgniter file upload application is ready. So you can access this by opening the following URL in your web browser.

http://localhost/type the CodeIgniter folder name here/
Download Source Code

Buddy! I hope you relished the tutorial, and it was good to see you again. Keep learning. Keep visiting.

Related Tutorials
View all