Upload image with codeigniter

upload-image-with-codeigniter

Hello World, This is ninth tutorial of the series Learn codeigniter from scratch. In the previous tutorial of this series, we have learned that how to perform update delete data in database with codeigniter. In this tutorial, we will learn how to upload image with codeigniter and save in database. From starting, we are performing all our code on todo list application. So this tutorial will also apply the code in todo list app.

I have divided this tutorial in following parts:

  • Concept Overview
  • Create view for uploading image
  • Perform action for uploading and saving image
  • Test application

Concept Overview

In this tutorial, we will upload image for every task. In this task we will add and update image with task. We will modify our previous code so that we can achieve our goal.


Create view for uploading image

  • Open todo.php, add.php and update.php file in application/views/todo folder. Update these files with following code.
<!DOCTYPE html>
<html>
<head>
	<title><?php echo $page_title; ?></title>
	<link rel="stylesheet" type="text/css" href="<?php echo base_url('public/bootstrap.min.css') ?>" />
	<!-- Include jquery -->
	<script type="text/javascript" src="<?php echo base_url('public/jquery-3.1.1.min.js') ?>"></script>
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-sm-8 col-sm-offset-2">
				<h1 class="page-header">To-Do List 
					<span class="badge"><?php echo $totalResult; ?></span>
					<a href="<?php echo site_url('todo/add'); ?>" class="btn btn-sm btn-danger pull-right">Add Task</a>
				</h1>
				<!-- Searching and sorting start -->
				<div class="page-header">
					<div class="row">
						<div class="col-xs-6">
							<form action="" method="get">
								<table class="table table-bordered">
									<tr>
										<th><input type="text" name="q" class="form-control" /></th>
										<th><input type="submit" class="btn btn-danger" /></th>
									</tr>
								</table>
							</form>
						</div>
						<div class="col-xs-6">
							<form action="" method="post">
								<table class="table table-bordered">
									<tr>
										<th><a href="<?php echo current_url(); ?>/?sort=desc">ASC to DESC</a></th>
										<th><a href="<?php echo current_url(); ?>/?sort=asc">DESC to ASC</a></th>
									</tr>
								</table>
							</form>
						</div>
					</div>
				</div>
				<!-- Searching and sorting close -->
				<table class="table table-striped table-bordered">
					<tr>
						<th>Task Image</th>
						<th>Task</th>
						<th>Status</th>
						<th>Complete Action</th>
						<th>Action</th>
					</tr>
					<?php
					if($content['bool']==true){
						foreach($content['d'] as $task){
							?>
							<tr>
								<td><img src="<?php echo base_url('uploads/').$task['task_img']; ?>" width="100" /></td>
								<td><?php echo $task['task_title']; ?></td>
								<td><?php echo $task['task_status']; ?></td>
								<td class="status-button"><button class="btn btn-<?php echo ($task['task_status']=='completed') ? 'success':'warning'; ?> btn-xs task-status-action" data-task_id="<?php echo $task['id']; ?>" data-task_status="<?php echo $task['task_status']; ?>"><?php echo $task['task_status']; ?></button></td>
								<td>
									<a href="<?php echo site_url('todo/update/'.$task['id']); ?>" class="btn btn-xs btn-primary">Edit</a>
									<a onclick="return confirm('Are you sure to delete data?')" href="<?php echo site_url('todo/delete/'.$task['id']); ?>" class="btn btn-xs btn-danger">Delete</a>
								</td>
							</tr>
							<?php
						}
					}else{
						?>
						<tr>
							<td colspan="4">
								<p class="alert alert-warning">No Data Found!!</p>
							</td>
						</tr>
						<?php
					}
					?>
				</table>
				<?php
					echo $this->pagination->create_links();
				?>
			</div>
		</div>
	</div>

<script>
	$(document).ready(function(){
		var ajaxUrl="<?php echo site_url(); ?>";
		$("td").on('click','button.task-status-action',function(){
			var task_id=$(this).data('task_id');
			var task_status=$(this).data('task_status');
			if(task_status=='pending'){
				var make_status='completed';
			}else{
				var make_status='pending';
			}
			var parentElm=$(this).parent();
			// Implement Jquery Ajax
			$.ajax({
				url:ajaxUrl+'/todo/ajax_change_status',
				type:"POST",
				data:{task_id:task_id,task_status:make_status},
				dataType:'json',
				success:function(response){
					parentElm.html(response.htmlData);
				}
			});
		});
	});
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
	<title><?php echo $page_title; ?></title>
	<link rel="stylesheet" type="text/css" href="<?php echo base_url('public/bootstrap.min.css') ?>" />
</head>
<body>
	<div class="container">
		<h1 class="page-header">Add Todo List 
			<a href="<?php echo site_url('todo'); ?>" class="btn btn-sm btn-danger pull-right">Task List</a>
		</h1>
		<p>
			<?php
			if(isset($msg)){
				echo $msg;
			}
			?>
		</p>
		<p><?php echo validation_errors(); ?></p>
		<form action="" method="post" enctype="multipart/form-data">
			<table class="table table-striped table-bordered">
				<tr>
					<th>Add Task</th>
					<td><input type="text" class="form-control" name="task_title" /></td>
				</tr>
				<tr>
					<th>Add Image</th>
					<td><input type="file" class="form-control" name="task_img" /></td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" class="btn btn-danger" value="Add Task" />
					</td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
	<title><?php echo $page_title; ?></title>
	<link rel="stylesheet" type="text/css" href="<?php echo base_url('public/bootstrap.min.css') ?>" />
</head>
<body>
	<div class="container">
		<h1 class="page-header">Edit Todo List 
			<a href="<?php echo site_url('todo'); ?>" class="btn btn-sm btn-danger pull-right">Task List</a>
		</h1>
		<p>
			<?php
			if(isset($msg)){
				echo $msg;
			}
			?>
		</p>
		<p><?php echo validation_errors(); ?></p>
		<form action="" method="post" enctype="multipart/form-data">
			<table class="table table-striped table-bordered">
				<tr>
					<th>Update Task</th>
					<td><input value="<?php echo $content['d']['task_title']; ?>" type="text" class="form-control" name="task_title" /></td>
				</tr>
				<tr>
					<th>Update Image</th>
					<td>
						<p><img src="<?php echo base_url('uploads/').$content['d']['task_img']; ?>" width="100" /></p>
						<input type="hidden" name="task_img" value="<?php echo $content['d']['task_img']; ?>" />
						<input type="file" class="form-control" name="task_img" />
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" class="btn btn-danger" value="Update Task" />
					</td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

Perform action for adding and updating image

  • Open Todo.php controller and Todo_Model model and replace these files with following code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Todo extends CI_Controller {
	function __construct(){
		parent::__construct();
		// Load Helper
		$this->load->helper('url');
		// Load Library
		$this->load->library('form_validation');
		$this->load->library('pagination');
		// Load Model
		$this->load->model('Todo_model');
	}
	// todo list
	function index($start=0){
		// Pagination Configuration Start
		$config['base_url'] = site_url('/todo/index');
		$config['total_rows'] = $this->Todo_model->count_list();
		$config['per_page'] = 5;
		$this->pagination->initialize($config);
		// Pagination Configuration End

		$data['page_title']="To-Do List";
		$data['totalResult']=$this->Todo_model->count_list();
		$data['content']=$this->Todo_model->get_all_list($start);
		$this->load->view('todo/todo.php',$data);
	}
	// Add todo list
	function add(){
		$data['page_title']="Add To-Do List";
		// Submit Form
		$this->form_validation->set_rules('task_title','Task Title','trim|required');
		if($this->form_validation->run()===true){
			// Upload Image
			$config['upload_path']          = './uploads/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;
            $this->load->library('upload', $config);
            if($this->upload->do_upload('task_img')){
           		$imageData=$this->upload->data();
		   		$img=$imageData['file_name'];
			}else{
				$img['file_name']='';
			}
			// Process the data
			$dbRes=$this->Todo_model->add($img);
			$data['msg']=$dbRes;
		}
		$this->load->view('todo/add.php',$data);
	}
	
	// Ajax Method
	function ajax_change_status(){
		echo json_encode($this->Todo_model->ajax_change_status());
	}

	// Update Data
	function update($id){
		$data['page_title']="Edit To-Do List";
		// Submit Form
		$this->form_validation->set_rules('task_title','Task Title','trim|required');
		if($this->form_validation->run()===true){

			// Upload Image
			$config['upload_path']          = './uploads/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;
            $this->load->library('upload', $config);
            if($this->upload->do_upload('task_img')){
           		$imageData=$this->upload->data();
		   		$img=$imageData['file_name'];
			}else{
				$img['file_name']=$this->input->post('task_img');
			}

			// Process the data
			$dbRes=$this->Todo_model->update($id,$img);
			$data['msg']=$dbRes;
		}
		$data['content']=$this->Todo_model->get_single_list($id);
		$this->load->view('todo/update.php',$data);
	}

	// Delete Data
	function delete($id){
		$dbRes=$this->Todo_model->delete($id);
		redirect('todo');
	}
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Todo_Model extends CI_Model{
	function __construct(){
		parent::__construct();
		// Load Database
		$this->load->database();
	}
	// Count Total List
	function count_list(){
		if(isset($_GET['q'])){
			$search=(string)$_GET['q'];
			$this->db->like('task_title',$search);
		}
		return $this->db->count_all_results('todo_list');
	}
	// Get all list
	function get_all_list($start){
		$response=array();
		$this->db->limit('5',$start);
		// Searching Implement
		if(isset($_GET['q'])){
			$search=(string)$_GET['q'];
			$this->db->like('task_title',$search);
		}
		if(isset($_GET['sort'])){
			$sort=(string)$_GET['sort'];
			$this->db->order_by('task_title',$sort);
		}
		$query=$this->db->get('todo_list');
		if($query->num_rows()>0){
			$response['bool']=true;
			$response['d']=$query->result_array();
		}else{
			$response['bool']=false;
		}
		return $response;
	}
	// Add Data
	function add($img){
		$insertData=array(
			'task_title'=>$this->input->post('task_title'),
			'task_status'=>'pending',
			'task_img'=>$img
		);
		$insertQuery=$this->db->insert('todo_list',$insertData);
		if($this->db->affected_rows()>0){
			return 'Data has been added';
		}else{
			return 'Data has not been added';
		}
	}

	// Change Status via AJax
	function ajax_change_status(){
		$res=array();
		$task_id=$this->input->post('task_id');
		$task_status=$this->input->post('task_status');
		$updateData=array(
			'task_status'=>$this->input->post('task_status')
		);
		$this->db->where('id',$task_id);
		$query=$this->db->update('todo_list',$updateData);
		if($this->db->affected_rows()>0){
			if($task_status=='pending'){
				$color='warning';
			}else{
				$color='success';
			}
			$res['bool']=true;
			$res['htmlData']='<button class="btn btn-'.$color.' btn-xs task-status-action" data-task_id="'.$task_id.'" data-task_status="'.$task_status.'">'.$task_status.'</button>';
		}else{
			$res['bool']=false;
			$res['htmlData']='<button class="btn btn-warning" btn-xs task-status-action" data-task_id="'.$task_id.'" data-task_status="'.$task_status.'">'.$task_status.'</button>';
		}
		return $res;
	}

	// Get Single list
	function get_single_list($id){
		$response=array();
		$this->db->where('id',$id);
		$query=$this->db->get('todo_list');
		if($query->num_rows()>0){
			$response['bool']=true;
			$response['d']=$query->row_array();
		}else{
			$response['bool']=false;
		}
		return $response;
	}

	// Update Data
	function update($id,$img){
		$updateData=array(
			'task_title'=>$this->input->post('task_title'),
			'task_status'=>'pending',
			'task_img'=>$img
		);
		$this->db->where('id',$id);
		$updateQuery=$this->db->update('todo_list',$updateData);
		if($this->db->affected_rows()>0){
			return 'Data has been updated';
		}else{
			return 'Data has not been updated';
		}
	}

	// Delete Data
	function delete($id){
		$res=array();
		$this->db->where('id',$id);
		$this->db->delete('todo_list');
	}
}
?>

In the above files we have apply the add and update action.

  • Create uploads folder on root.
  • Create task_img field in database table.

Test the application

  • Now open the application in browser. You will see the following screens.

 

upload-image

Congratulations, we have successfully created tutorial for how to upload image with codeigniter.

Leave a Reply