Multiple image upload with view, edit and delete in codeigniter | 2my4edge

15 April 2016

Multiple image upload with view, edit and delete in codeigniter

Simple way to upload multiple image upload view, edit and delete everything in codeigniter, this is one of the best way create a multiple image upload files with text also. Here i'm going to tell you a simple method for this multiple image upload and edit delete. Let see the step by step process and coding.

Multiple image upload edit and delete
LIVE DEMO           DOWNLOAD

FOR BASIC SETTING OF CODEIGNITER

BASIC SETTING
application->config->autoload.php file
$autoload['libraries'] = array('database', 'email', 'session', 'upload');

FOLDER STRUCTURE IMAGE

Multiple image upload edit and delete structure

DATABASE DETAILS

Database Name : 2my4edge
Table Names : 
  1.photos
  2.user
1.photos
CREATE TABLE `photos` (
  `id` int(11) NOT NULL,
  `image` varchar(350) NOT NULL,
  `user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2.user
CREATE TABLE `user` (
  `u_id` int(11) NOT NULL,
  `name` varchar(350) NOT NULL,
  `class` varchar(350) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

VIEW FILES 
In View we need 3 files
1. Insert
2. View
3. Edit

INSERT FILE
That i kept file name as welcome_message.php file
<div align="center" class="container">
<form method="POST" action="<?php echo site_url('welcome/file_upload');?>" enctype='multipart/form-data'>
<table border="1">
<tr>
<td>Name</td>
<td><input type="text" name="name" required id="name" placeholder="Name"></td>
</tr>
<tr>
<td>Class</td>
<td><input type="text" name="class" required id="class" placeholder="Class"></td>
</tr>
<tr>
<td>Images</td>
<td><input type="file" name="userfile[]" required id="image_file" accept=".png,.jpg,.jpeg,.gif" multiple></td>
</tr>
<tr>
<td colspan="2" align="center"><input style="width: 50%;" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>

VIEW FILE
View all the data. i kept that file name as view.php
<div align="center" class="container">
<p align="center"><a href="<?php echo base_url(); ?>">Upload new data</a></p>
<table border="1" style="width:100%">
  <tr>
    <td>S.No</td>
    <td>Name</td> 
    <td>Class</td>
    <td>Edit</td>
  </tr>
  <?php
    if(isset($view_data) && is_array($view_data) && count($view_data)): $i=1;
    foreach ($view_data as $key => $data) { 
    ?>
  <tr>
    <td><?php echo $i++ ?></td>
    <td><?php echo $data['name']; ?></td> 
    <td><?php echo $data['class']; ?></td>
    <td><a href="<?php echo site_url(); ?>/welcome/edit/<?php echo $data['u_id']; ?>">Edit</a></td>
  </tr>
  <?php } endif; ?>
</table>
</div>

EDIT FILE
To edit the data. File name is edit.php
<div align="center" class="container">
<form method="POST" action="<?php echo site_url('welcome/edit_file_upload');?>" enctype='multipart/form-data'>
<table border="1">
<?php
    if(isset($edit_data) && is_array($edit_data) && count($edit_data)): $i=1;
    foreach ($edit_data as $key => $data) { 
  ?>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $data['name']; ?>" id="file" placeholder="name"></td>
</tr>
<tr>
<td>Class</td>
<td><input type="text" name="class" value="<?php echo $data['class']; ?>" id="file" placeholder="class"></td>
<input type="hidden" name="user_id" value="<?php echo $data['u_id']; ?>" id="file" placeholder="class">
</tr>
<?php } endif; ?>
<?php
    if(isset($edit_data_image) && is_array($edit_data) && count($edit_data)): $i=1;
    foreach ($edit_data_image as $key => $data) { 
  ?>
<tr class="imagelocation<?php echo $data['id'] ?>">
<td colspan="2" align="center">
<img src="<?php echo base_url(); ?>uploads/<?php echo $data['image']; ?>" style="vertical-align:middle;" width="80" height="80">
<span style="cursor:pointer;" onclick="javascript:deleteimage(<?php echo $data['id'] ?>)">X</span>
</td>
</tr>
<?php }endif; ?>
<tr>
<td>Images</td>
<td><input type="file" name="userfile[]" id="image_file" accept=".png,.jpg,.jpeg,.gif" multiple></td>
</tr>
<tr>
<td colspan="2" align="center"><input style="width: 50%;" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>

DELETE IN EDIT FILE ITSELF, AJAX DELETE
add this code also in edit.php file itself
<script type="text/javascript">
function deleteimage(image_id)
{
var answer = confirm ("Are you sure you want to delete from this post?");
if (answer)
{
        $.ajax({
                type: "POST",
                url: "<?php echo site_url('welcome/deleteimage');?>",
                data: "image_id="+image_id,
                success: function (response) {
                  if (response == 1) {
                    $(".imagelocation"+image_id).remove(".imagelocation"+image_id);
                  };
                  
                }
            });
      }
}
</script>

CONTROLLER
Welcome.php file Welcome controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');                    /***** LOADING HELPER TO AVOID PHP ERROR ****/
        $this->load->model('Welcome_model','welcome'); /* LOADING MODEL * Welcome_model as welcome */
    }

    public function index()
    {
        $this->load->view('welcome_message');
    }

    public function file_upload(){
              $files = $_FILES;
              $count = count($_FILES['userfile']['name']);
              for($i=0; $i<$count; $i++)
                {
                $_FILES['userfile']['name']= time().$files['userfile']['name'][$i];
                $_FILES['userfile']['type']= $files['userfile']['type'][$i];
                $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
                $_FILES['userfile']['error']= $files['userfile']['error'][$i];
                $_FILES['userfile']['size']= $files['userfile']['size'][$i];
                $config['upload_path'] = './uploads/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = '2000000';
                $config['remove_spaces'] = true;
                $config['overwrite'] = false;
                $config['max_width'] = '';
                $config['max_height'] = '';
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                $this->upload->do_upload();
                $fileName = $_FILES['userfile']['name'];
                $images[] = $fileName;
                }
                  $fileName = implode(',',$images);
                  $this->welcome->upload_image($this->input->post(),$fileName);
                  redirect('welcome/view');
                }

        public function view(){
            $this->data['view_data']= $this->welcome->view_data();
            $this->load->view('view', $this->data, FALSE);
                }

        public function edit($edit_id){
            $this->data['edit_data']= $this->welcome->edit_data($edit_id);
            $this->data['edit_data_image']= $this->welcome->edit_data_image($edit_id);
            $this->load->view('edit', $this->data, FALSE);
                }

        public function deleteimage(){
            $deleteid  = $this->input->post('image_id');
            $this->db->delete('photos', array('id' => $deleteid)); 
            $verify = $this->db->affected_rows();
            echo $verify;

        }


       public function edit_file_upload(){
              $files = $_FILES;
              if(!empty($files['userfile']['name'][0])){
              $count = count($_FILES['userfile']['name']);
              $user_id = $this->input->post('user_id');
              for($i=0; $i<$count; $i++)
                {
                $_FILES['userfile']['name']= time().$files['userfile']['name'][$i];
                $_FILES['userfile']['type']= $files['userfile']['type'][$i];
                $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
                $_FILES['userfile']['error']= $files['userfile']['error'][$i];
                $_FILES['userfile']['size']= $files['userfile']['size'][$i];
                $config['upload_path'] = './uploads/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = '2000000';
                $config['remove_spaces'] = true;
                $config['overwrite'] = false;
                $config['max_width'] = '';
                $config['max_height'] = '';
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                $this->upload->do_upload();
                $fileName = $_FILES['userfile']['name'];
                $images[] = $fileName;
                }
                  $fileName = implode(',',$images);
                  $this->welcome->edit_upload_image($user_id,$this->input->post(),$fileName);
                }else
                {
              $user_id = $this->input->post('user_id');
              $this->welcome->edit_upload_image($user_id,$this->input->post());
                }
                redirect('welcome/view');
                }
    }

MODEL
Welcome_model.php file
<?php
class Welcome_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function upload_image($inputdata,$filename)
    {
      $this->db->insert('user', $inputdata); 
      $insert_id = $this->db->insert_id();
      if($filename!='' ){
      $filename1 = explode(',',$filename);
      foreach($filename1 as $file){
      $file_data = array(
      'image' => $file,
      'user_id' => $insert_id
      );
      $this->db->insert('photos', $file_data);
      }
      }
    }

    public function view_data(){
        $query=$this->db->query("SELECT ud.*
                                 FROM user ud 
                                 ORDER BY ud.u_id DESC");
        return $query->result_array();
    }

    public function edit_data($id){
        $query=$this->db->query("SELECT ud.*
                                 FROM user ud 
                                 WHERE ud.u_id = $id");
        return $query->result_array();
    }

    public function edit_data_image($id){
        $query=$this->db->query("SELECT photo.*
                                 FROM user ud 
                                 RIGHT JOIN photos as photo
                                 ON ud.u_id = photo.user_id 
                                 WHERE ud.u_id = $id");
        return $query->result_array();
    }

    public function edit_upload_image($user_id,$inputdata,$filename ='')
    {

        $data = array('name'                   => $inputdata['name'],
                      'class'                  => $inputdata['class']);
        $this->db->where('u_id', $user_id);
        $this->db->update('user', $data);

      if($filename!='' ){
      $filename1 = explode(',',$filename);
      foreach($filename1 as $file){
      $file_data = array(
      'image' => $file,
      'user_id' => $user_id
      );
      $this->db->insert('photos', $file_data);
      }
      }
    }

}

I hope this post will be really helpful to all codeingniter developer. Thanks for visiting. Keep in touch with us in Social media for more future updates.





RELATED POSTS :

30 comments:

  1. Nice one better use codeigniter my model library.

    ReplyDelete
    Replies
    1. Yes. that is also a fine way @Karthick muthu

      Delete
  2. why image cannot uploaded?

    ReplyDelete
  3. why image cannot be uploaded?

    ReplyDelete
    Replies
    1. What Kinda Error your Getting @Christine naibaho.?.

      Delete
  4. I have voice's in my hand ✋, they can't to me, they understand, they can't to me,
    WhatsApp dude,
    What's going on, how's your blog going on? BTW I like the tutorial

    Keep rocking...

    ReplyDelete
  5. not delete for image plzz anybody tell for suggestions...

    ReplyDelete
  6. Sorry i can not upload image and it show Object not found!

    The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

    If you think this is a server error, please contact the webmaster.

    ReplyDelete
  7. Hi,

    Why the images are not uploaded to the directory?

    ReplyDelete
  8. Instead of $this->upload->do_upload(); in the file_upload() in controller use $this->upload->do_upload('userfile');
    problem is fixed :)

    ReplyDelete
  9. Instead of $this->upload->do_upload(); in the file_upload function in welcome controller use $this->upload->do_upload('userfile');

    ReplyDelete
  10. undefined userfile error i got what should i do?

    ReplyDelete
  11. Hello,

    I'm confuse with this:

    query("SELECT photo.*
    FROM user ud
    RIGHT JOIN photos as photo
    ON ud.u_id = photo.user_id
    WHERE ud.u_id = $id");

    What does ud stands for??? is it a naming convention for table column???

    ReplyDelete
  12. query("SELECT photo.* FROM user ud ON ud.u_id = photo.user_id WHERE ud.u_id = $id");

    I'm confuse with the query.. what does ud stands for????

    ReplyDelete
  13. Great script, thanks for sharing. Just a couple of questions: can I use it to upload more files then images? I mean PDF, zip and so on. Second question: is it possible to add a progress bar or any message to display the ongoing upload? Thanks a lot

    ReplyDelete
  14. Error Number: 1054

    Unknown column 'name' in 'field list'

    INSERT INTO `photos` (`name`, `class`) VALUES ('sdgf', 'adsg')

    Filename: E:/xampp/htdocs/upload/application/models/Welcome_model.php

    Line Number: 11


    i am sory.... i get the problem... you can help me??

    ReplyDelete
  15. can you please tell me the purpose of using "ud" in database query in model

    ReplyDelete
    Replies
    1. ud is variable of user. we defined user as ud in mysql.

      Delete
  16. Gives and error of
    A PHP Error was encountered

    Severity: Notice

    Message: Undefined index: userfile

    Filename: controllers/Welcome.php

    Line Number: 36

    Backtrace:

    File: /var/www/html/image_upload/application/controllers/Welcome.php
    Line: 36
    Function: _error_handler

    File: /var/www/html/image_upload/index.php
    Line: 315
    Function: require_once

    ReplyDelete
  17. In order for the author script to function correctly, there is a need to change the database and add the primary key and auto increment



    CREATE TABLE `photos` (
    `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `image` varchar(350) NOT NULL,
    `user_id` int(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    CREATE TABLE `user` (
    `u_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `name` varchar(350) NOT NULL,
    `class` varchar(350) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    ReplyDelete

  18. By the way, I was forgetting, thank you for having made this wonderful article available, although the post is a little old, this simple statement took away a doubt that was having a few months, it is difficult to find decent material on the internet.

    Thank you again.

    ReplyDelete
  19. in helper try adding 'file' to autoload

    ReplyDelete
  20. how to display the upload pictures?
    please i need answer :(

    ReplyDelete
  21. upload multiple files database insert a file name in same row .....
    how to give a code?

    ReplyDelete
  22. Really Save my day thanks alot for your tutorial really very nice for understand.

    ReplyDelete
  23. Really save my day am work hard on updating images from 4 days final i get rid off this thanks alot and really nice tutorial for understading

    ReplyDelete
  24. hi sorry but i have a problem when i try modific a register, show all register and modific all :s

    pd: somebody spanish

    ReplyDelete
  25. A Database Error Occurred
    Error Number: 1054

    Unknown column 'ud.u_id' in 'where clause'

    SELECT ud.* FROM user ud WHERE ud.u_id = 22

    Filename: E:/xampp/htdocs/ci/application/models/Welcome_model.php

    Line Number: 36

    ReplyDelete

^