Multiple Image Upload with View, Edit and Delete in CodeIgniter

The image upload feature is the most used functionality in the dynamic web application. Multiple images upload feature helps to upload a large number of files to the server at once. Upload multiple images in CodeIgniter allows uploading multiple images at once instead of one-by-one. This feature is very useful for the data management section where the multiple images needs to be uploaded for each record.

CodeIgniter’s File Uploading Class provides an easy way to upload file to the server. You can integrate the multiple image upload functionality with Upload library in CodeIgniter. In this tutorial, we will show you how to integrate multiple image upload with the view, edit, and delete functionality in CodeIgniter.

To demonstrate the multiple images upload management functionality, we will develop a Gallery CRUD system in CodeIgniter. It allows the user to upload multiple images with data and store in the database in the CodeIgniter framework.

In the sample CodeIgniter application, we will implement a gallery management system with multiple images in the CodeIgniter framework.

  • Fetch the gallery data from the database and list on the webpage.
  • Upload multiple images to the server and insert form data to the database.
  • View gallery with multiple images.
  • Edit and update multiple images.
  • Delete gallery and multiple images.

Before getting started to integrate multiple image upload management in CodeIgniter, take a look at the files structure.

codeigniter_gallery_crud/
├── application/
│   ├── controllers/
│   │   └── Manage_gallery.php
│   ├── models/
│   │   └── Gallery.php
│   ├── views/
│   │   ├── gallery/
│   │   │   ├── index.php
│   │   │   ├── view.php
│   │   │   └── add-edit.php
│   │   └── templates/
│   │       ├── header.php
│   │       └── footer.php
├── assets/
│   ├── bootstrap/
│   │   └── bootstrap.min.css
│   ├── js/
│   │   └── jquery.min.js
│   ├── css/
│   │   └── style.css
│   └── images/
└── uploads/
    └── images/

Create Database Tables

To store the gallery data and image files information two tables are required in the database.

1. The following SQL creates a gallery table with some basic fields in the MySQL database.

CREATE TABLE `gallery` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

2. The following SQL creates a gallery_images table with parent gallery identifier field (gallery_id) in the MySQL database.

CREATE TABLE `gallery_images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `gallery_id` int(11) NOT NULL,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config

autoload.php
In the config/autoload.php file, define the library and helper to load automatically on every request which will be used frequently in the application.

$autoload['libraries'] = array('database''session'); 
$autoload['helper'] = array('url');

Controller (Manage_gallery.php)

The Manage_gallery controller handles the CRUD operations (view, add, edit, and delete) of the gallery and images.

  • __construct()
    • Load the form helper and validation library.
    • Load the gallery model.
    • Define default controller name.
  • index()
    • Retrieve status messages from SESSION.
    • Fetch the records from the database using getRows() method of Gallery model.
    • Pass the gallery data and load the list view.
  • view()
    • Fetch the gallery data from the database based on the specific ID.
    • Pass the gallery data and load the details view.
  • add()
    • Initially, the form view is loaded to receive input of the gallery and files.
    • If the form is submitted,
      • The posted form data is validated using CodeIgniter Form Validation library.
      • Insert gallery data in the database using insert() method of Gallery model.
      • Upload multiple images to the server using CodeIgniter Upload library.
      • Insert uploaded files information in the database using insertImage() method of Gallery model.
  • edit()
    • Fetch the gallery data from the database based on the specific ID.
    • The form view is loaded with the pre-filled gallery data and images.
    • If the form is submitted,
      • The posted form data is validated using CodeIgniter Form Validation library.
      • Update gallery data in the database using update() method of Gallery model.
      • Upload selected images to the server using CodeIgniter Upload library.
  • block() – Update the status of the gallery to Inactive.
  • unblock() – Update the status of the gallery to Active.
  • delete()
    • Remove gallery data from the database using delete() method of Gallery model.
    • Remove images data from the database using deleteImage() method of Gallery model.
    • Remove the image files from the server.
  • deleteImage() – This functionality is called by the Ajax request to delete specific image data from the database as well as the server.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class 
Manage_gallery extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
        
// Load form helper and form validation library
        
$this->load->helper('form');
        
$this->load->library('form_validation');
        
        
// Load gallery model
        
$this->load->model('gallery');
        
        
// Default controller name
        
$this->controller 'manage_gallery';
    }
    
    public function 
index(){
        
$data = array();
        
        
// Get messages from the session
        
if($this->session->userdata('success_msg')){
            
$data['success_msg'] = $this->session->userdata('success_msg');
            
$this->session->unset_userdata('success_msg');
        }
        if(
$this->session->userdata('error_msg')){
            
$data['error_msg'] = $this->session->userdata('error_msg');
            
$this->session->unset_userdata('error_msg');
        }

        
$data['gallery'] = $this->gallery->getRows();
        
$data['title'] = 'Gallery Archive';
        
        
// Load the list page view
        
$this->load->view('templates/header'$data);
        
$this->load->view('gallery/index'$data);
        
$this->load->view('templates/footer');
    }
    
    public function 
view($id){
        
$data = array();
        
        
// Check whether id is not empty
        
if(!empty($id)){
            
$data['gallery'] = $this->gallery->getRows($id);
            
$data['title'] = $data['gallery']['title'];
            
            
// Load the details page view
            
$this->load->view('templates/header'$data);
            
$this->load->view('gallery/view'$data);
            
$this->load->view('templates/footer');
        }else{
            
redirect($this->controller);
        }
    }
    
    public function 
add(){
        
$data $galleryData = array();
        
$errorUpload '';
        
        
// If add request is submitted
        
if($this->input->post('imgSubmit')){
            
// Form field validation rules
            
$this->form_validation->set_rules('title''gallery title''required');
            
            
// Prepare gallery data
            
$galleryData = array(
                
'title' => $this->input->post('title')
            );
            
            
// Validate submitted form data
            
if($this->form_validation->run() == true){
                
// Insert gallery data
                
$insert $this->gallery->insert($galleryData);
                
$galleryID $insert
                
                if(
$insert){
                    if(!empty(
$_FILES['images']['name'])){
                        
$filesCount count($_FILES['images']['name']);
                        for(
$i 0$i $filesCount$i++){
                            
$_FILES['file']['name']     = $_FILES['images']['name'][$i];
                            
$_FILES['file']['type']     = $_FILES['images']['type'][$i];
                            
$_FILES['file']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
                            
$_FILES['file']['error']    = $_FILES['images']['error'][$i];
                            
$_FILES['file']['size']     = $_FILES['images']['size'][$i];
                            
                            
// File upload configuration
                            
$uploadPath 'uploads/images/';
                            
$config['upload_path'] = $uploadPath;
                            
$config['allowed_types'] = 'jpg|jpeg|png|gif';
                            
                            
// Load and initialize upload library
                            
$this->load->library('upload'$config);
                            
$this->upload->initialize($config);
                            
                            
// Upload file to server
                            
if($this->upload->do_upload('file')){
                                
// Uploaded file data
                                
$fileData $this->upload->data();
                                
$uploadData[$i]['gallery_id'] = $galleryID;
                                
$uploadData[$i]['file_name'] = $fileData['file_name'];
                                
$uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
                            }else{
                                
$errorUpload .= $fileImages[$key].'('.$this->upload->display_errors('''').') | '
                            }
                        }
                        
                        
// File upload error message
                        
$errorUpload = !empty($errorUpload)?' Upload Error: '.trim($errorUpload' | '):'';
                        
                        if(!empty(
$uploadData)){
                            
// Insert files info into the database
                            
$insert $this->gallery->insertImage($uploadData);
                        }
                    }
                    
                    
$this->session->set_userdata('success_msg''Gallery has been added successfully.'.$errorUpload);
                    
redirect($this->controller);
                }else{
                    
$data['error_msg'] = 'Some problems occurred, please try again.';
                }
            }
        }
        
        
$data['gallery'] = $galleryData;
        
$data['title'] = 'Create Gallery';
        
$data['action'] = 'Add';
        
        
// Load the add page view
        
$this->load->view('templates/header'$data);
        
$this->load->view('gallery/add-edit'$data);
        
$this->load->view('templates/footer');
    }
    
    public function 
edit($id){
        
$data $galleryData = array();
        
        
// Get gallery data
        
$galleryData $this->gallery->getRows($id);
        
        
// If update request is submitted
        
if($this->input->post('imgSubmit')){
            
// Form field validation rules
            
$this->form_validation->set_rules('title''gallery title''required');
            
            
// Prepare gallery data
            
$galleryData = array(
                
'title' => $this->input->post('title')
            );
            
            
// Validate submitted form data
            
if($this->form_validation->run() == true){
                
// Update gallery data
                
$update $this->gallery->update($galleryData$id);

                if(
$update){
                    if(!empty(
$_FILES['images']['name'])){
                        
$filesCount count($_FILES['images']['name']);
                        for(
$i 0$i $filesCount$i++){
                            
$_FILES['file']['name']     = $_FILES['images']['name'][$i];
                            
$_FILES['file']['type']     = $_FILES['images']['type'][$i];
                            
$_FILES['file']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
                            
$_FILES['file']['error']    = $_FILES['images']['error'][$i];
                            
$_FILES['file']['size']     = $_FILES['images']['size'][$i];
                            
                            
// File upload configuration
                            
$uploadPath 'uploads/images/';
                            
$config['upload_path'] = $uploadPath;
                            
$config['allowed_types'] = 'jpg|jpeg|png|gif';
                            
                            
// Load and initialize upload library
                            
$this->load->library('upload'$config);
                            
$this->upload->initialize($config);
                            
                            
// Upload file to server
                            
if($this->upload->do_upload('file')){
                                
// Uploaded file data
                                
$fileData $this->upload->data();
                                
$uploadData[$i]['gallery_id'] = $id;
                                
$uploadData[$i]['file_name'] = $fileData['file_name'];
                                
$uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
                            }else{
                                
$errorUpload .= $fileImages[$key].'('.$this->upload->display_errors('''').') | '
                            }
                        }
                        
                        
// File upload error message
                        
$errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUpload' | '):'';
                        
                        if(!empty(
$uploadData)){
                            
// Insert files data into the database
                            
$insert $this->gallery->insertImage($uploadData);
                        }
                    }

                    
$this->session->set_userdata('success_msg''Gallery has been updated successfully.'.$errorUpload);
                    
redirect($this->controller);
                }else{
                    
$data['error_msg'] = 'Some problems occurred, please try again.';
                }
            }
        }

        
        
$data['gallery'] = $galleryData;
        
$data['title'] = 'Update Gallery';
        
$data['action'] = 'Edit';
        
        
// Load the edit page view
        
$this->load->view('templates/header'$data);
        
$this->load->view('gallery/add-edit'$data);
        
$this->load->view('templates/footer');
    }
    
    public function 
block($id){
        
// Check whether gallery id is not empty
        
if($id){
            
// Update gallery status
            
$data = array('status' => 0);
            
$update $this->gallery->update($data$id);
            
            if(
$update){
                
$this->session->set_userdata('success_msg''Gallery has been blocked successfully.');
            }else{
                
$this->session->set_userdata('error_msg''Some problems occurred, please try again.');
            }
        }

        
redirect($this->controller);
    }
    
    public function 
unblock($id){
        
// Check whether gallery id is not empty
        
if($id){
            
// Update gallery status
            
$data = array('status' => 1);
            
$update $this->gallery->update($data$id);
            
            if(
$update){
                
$this->session->set_userdata('success_msg''Gallery has been activated successfully.');
            }else{
                
$this->session->set_userdata('error_msg''Some problems occurred, please try again.');
            }
        }

        
redirect($this->controller);
    }
    
    public function 
delete($id){
        
// Check whether id is not empty
        
if($id){
            
$galleryData $this->gallery->getRows($id);
            
            
// Delete gallery data
            
$delete $this->gallery->delete($id);
            
            if(
$delete){
                
// Delete images data 
                
$condition = array('gallery_id' => $id); 
                
$deleteImg $this->gallery->deleteImage($condition); 
                 
                
// Remove files from the server 
                
if(!empty($galleryData['images'])){ 
                    foreach(
$galleryData['images'] as $img){ 
                        @
unlink('uploads/images/'.$img['file_name']); 
                    } 
                } 
                
                
$this->session->set_userdata('success_msg''Gallery has been removed successfully.');
            }else{
                
$this->session->set_userdata('error_msg''Some problems occurred, please try again.');
            }
        }

        
redirect($this->controller);
    }
    
    public function 
deleteImage(){
        
$status  'err'
        
// If post request is submitted via ajax
        
if($this->input->post('id')){
            
$id $this->input->post('id');
            
$imgData $this->gallery->getImgRow($id);
            
            
// Delete image data
            
$con = array('id' => $id);
            
$delete $this->gallery->deleteImage($con);
            
            if(
$delete){
                
// Remove files from the server 
                
@unlink('uploads/images/'.$imgData['file_name']); 
                
$status 'ok'
            }
        }
        echo 
$status;die; 
    }
}

Model (Gallery.php)

The Gallery model handles the database related operations (Fetch, Add, Edit, and Delete).

  • __construct() – Define the table names.
  • getRows()
    • Fetch the gallery data from the database based on the specified parameters passed in the $params.
    • For all records, it returns the data with the default image of the respective gallery.
    • For a single record, it returns the specific gallery data with all the images of the respective gallery.
  • getImgRow() – Fetch image file information based on the specified row ID.
  • insert() – Insert gallery data in the database. Returns the row ID on success, and FALSE on error.
  • insertImage() – Insert image file information in the database. Returns the row ID on success, and FALSE on error.
  • update() – Update gallery data in the database based on the row ID. Returns TRUE on success, and FALSE on error.
  • delete() – Delete record from the database based on the row ID. Returns TRUE on success, and FALSE on error.
  • deleteImage() – Delete single/bulk images from the database based on the specified conditions.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class 
Gallery extends CI_Model{
    
    function 
__construct() {
        
$this->galleryTbl   'gallery';
        
$this->imgTbl 'gallery_images';
    }
    
    
/*
     * Fetch gallery data from the database
     * @param id returns a single record if specified, otherwise all records
     */
    
public function getRows($id ''){
        
$this->db->select("*, (SELECT file_name FROM ".$this->imgTbl." WHERE gallery_id = ".$this->galleryTbl.".id ORDER BY id DESC LIMIT 1) as default_image");
        
$this->db->from($this->galleryTbl);
        if(
$id){
            
$this->db->where('id'$id);
            
$query  $this->db->get();
            
$result = ($query->num_rows() > 0)?$query->row_array():array();
            
            if(!empty(
$result)){
                
$this->db->select('*');
                
$this->db->from($this->imgTbl);
                
$this->db->where('gallery_id'$result['id']);
                
$this->db->order_by('id''desc');
                
$query  $this->db->get();
                
$result2 = ($query->num_rows() > 0)?$query->result_array():array();
                
$result['images'] = $result2
            } 
        }else{
            
$this->db->order_by('id''desc');
            
$query  $this->db->get();
            
$result = ($query->num_rows() > 0)?$query->result_array():array();
        }
        
        
// return fetched data
        
return !empty($result)?$result:false;
    }
    
    
/*
     * Fetch image data from the database
     * @param id returns a single record
     */
    
public function getImgRow($id){
        
$this->db->select('*');
        
$this->db->from($this->imgTbl);
        
$this->db->where('id'$id);
        
$query  $this->db->get();
        return (
$query->num_rows() > 0)?$query->row_array():false;
    }
    
    
/*
     * Insert gallery data into the database
     * @param $data data to be insert based on the passed parameters
     */
    
public function insert($data = array()) {
        if(!empty(
$data)){
            
// Add created and modified date if not included
            
if(!array_key_exists("created"$data)){
                
$data['created'] = date("Y-m-d H:i:s");
            }
            if(!
array_key_exists("modified"$data)){
                
$data['modified'] = date("Y-m-d H:i:s");
            }
            
            
// Insert gallery data
            
$insert $this->db->insert($this->galleryTbl$data);
            
            
// Return the status
            
return $insert?$this->db->insert_id():false;
        }
        return 
false;
    }
    
    
/*
     * Insert image data into the database
     * @param $data data to be insert based on the passed parameters
     */
    
public function insertImage($data = array()) {
        if(!empty(
$data)){
            
            
// Insert gallery data
            
$insert $this->db->insert_batch($this->imgTbl$data);
            
            
// Return the status
            
return $insert?$this->db->insert_id():false;
        }
        return 
false;
    }
    
    
/*
     * Update gallery data into the database
     * @param $data array to be update based on the passed parameters
     * @param $id num filter data
     */
    
public function update($data$id) {
        if(!empty(
$data) && !empty($id)){
            
// Add modified date if not included
            
if(!array_key_exists("modified"$data)){
                
$data['modified'] = date("Y-m-d H:i:s");
            }
            
            
// Update gallery data
            
$update $this->db->update($this->galleryTbl$data, array('id' => $id));
            
            
// Return the status
            
return $update?true:false;
        }
        return 
false;
    }
    
    
/*
     * Delete gallery data from the database
     * @param num filter data based on the passed parameter
     */
    
public function delete($id){
        
// Delete gallery data
        
$delete $this->db->delete($this->galleryTbl, array('id' => $id));
        
        
// Return the status
        
return $delete?true:false;
    }
    
    
/*
     * Delete image data from the database
     * @param array filter data based on the passed parameter
     */
    
public function deleteImage($con){
        
// Delete image data
        
$delete $this->db->delete($this->imgTbl$con);
        
        
// Return the status
        
return $delete?true:false;
    }
    
}

Views

1. templates/
The views/templates/ directory holds the element parts (header, footer, etc.) of the web templates.

1.1. templates/header.php
This file holds the header section of the web page. The Bootstrap 4 library is used for styling the HTML table and form. So, include the CSS file of the Bootstrap library and the custom stylesheet file (if any).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?php echo $title?> | Multiple Images Management in CodeIgniter</title>
    
    <!-- Bootstrap library -->
    <link rel="stylesheet" href="<?php echo base_url('assets/bootstrap/bootstrap.min.css'); ?>">
    <script src="<?php echo base_url('assets/bootstrap/bootstrap.min.js'); ?>"></script>
    
    <!-- Stylesheet file -->
    <link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>">
</head>
<body>

1.2. templates/footer.php
This file holds the footer section of the web page.

</body>
</html>

2. gallery/
The views/gallery/ directory holds the view files of the Manage_gallery controller.

2.1. gallery/index.php
Initially, all the gallery data is retrieved from the database and listed in a tabular view with the Add, Edit, and Delete options.

  • The View link displays the selected gallery info with images.
  • The Add link allows to add gallery information and upload multiple images.
  • The Edit link allows to edit gallery info and upload/delete images from the gallery.
  • The Delete link allows deleting gallery and images from the database.
  • The Status badge (Active/Inactive) allows controlling the visibility of the gallery.
<div class="container">
    <h2>Multiple Images Management</h2>
	
    <!-- Display status message -->
    <?php if(!empty($success_msg)){ ?>
    <div class="col-xs-12">
        <div class="alert alert-success"><?php echo $success_msg?></div>
    </div>
    <?php }elseif(!empty($error_msg)){ ?>
    <div class="col-xs-12">
        <div class="alert alert-danger"><?php echo $error_msg?></div>
    </div>
    <?php ?>
	
    <div class="row">
        <div class="col-md-12 head">
            <h5><?php echo $title?></h5>
            <!-- Add link -->
            <div class="float-right">
                <a href="<?php echo base_url('manage_gallery/add'); ?>" class="btn btn-success"><i class="plus"></i> New Gallery</a>
            </div>
        </div>
        
        <!-- Data list table --> 
        <table class="table table-striped table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th width="5%">#</th>
                    <th width="10%"></th>
                    <th width="40%">Title</th>
                    <th width="19%">Created</th>
                    <th width="8%">Status</th>
                    <th width="18%">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($gallery)){ $i=0
                    foreach(
$gallery as $row){ $i++;
                        
$defaultImage = !empty($row['default_image'])?'<img src="'.base_url().'uploads/images/'.$row['default_image'].'" alt="" />':'';
                        
$statusLink = ($row['status'] == 1)?site_url('manage_gallery/block/'.$row['id']):site_url('manage_gallery/unblock/'.$row['id']); 
                        
$statusTooltip = ($row['status'] == 1)?'Click to Inactive':'Click to Active'
                
?> <tr> <td><?php echo $i?></td> <td><?php echo $defaultImage?></td> <td><?php echo $row['title']; ?></td> <td><?php echo $row['created']; ?></td> <td><a href="<?php echo $statusLink?>" title="<?php echo $statusTooltip?>"><span class="badge <?php echo ($row['status'] == 1)?'badge-success':'badge-danger'?>"><?php echo ($row['status'] == 1)?'Active':'Inactive'?></span></a></td> <td> <a href="<?php echo base_url('manage_gallery/view/'.$row['id']); ?>" class="btn btn-primary">view</a> <a href="<?php echo base_url('manage_gallery/edit/'.$row['id']); ?>" class="btn btn-warning">edit</a> <a href="<?php echo base_url('manage_gallery/delete/'.$row['id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?true:false;">delete</a> </td> </tr> <?php } }else{ ?> <tr><td colspan="6">No gallery found...</td></tr> <?php ?> </tbody> </table> </div> </div>

Delete Gallery Image via AJAX:
In the view.php and add-edit.php files, the image deletes functionality is integrated. The jQuery is used to delete images from the gallery via Ajax.

Where the gallery images delete functionality is used, include the jQuery library.

<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>

The deleteImage() function initiate AJAX request to delete image from gallery.

  • POST the file ID to the deleteImage() method of the Manage_gallery controller.
  • Based on the status, remove the specific image from the web page using jQuery remove() method.
<script>
function deleteImage(id){
    var result = confirm("Are you sure to delete?");
    if(result){
        $.post( "<?php echo base_url('manage_gallery/deleteImage'); ?>", {id:id}, function(resp) {
            if(resp == 'ok'){
                $('#imgb_'+id).remove();
                alert('The image has been removed from the gallery');
            }else{
                alert('Some problem occurred, please try again.');
            }
        });
    }
}
</script>

2.2. gallery/view.php
This view file is loaded by the view() function of Manage_gallery controller. The specific gallery details are displayed on the webpage.

  • All the images from the selected gallery are listed with the Delete link.
  • Once the Delete button is clicked, JavaScript deleteImage() function is triggered and the respective image is removed from the gallery via Ajax using jQuery.
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h5><?php echo !empty($gallery['title'])?$gallery['title']:''?></h5>
			
            <?php if(!empty($gallery['images'])){ ?>
                <div class="gallery-img">
                <?php foreach($gallery['images'] as $imgRow){ ?>
                    <div class="img-box" id="imgb_<?php echo $imgRow['id']; ?>">
                        <img src="<?php echo base_url('uploads/images/'.$imgRow['file_name']); ?>">
                        <a href="javascript:void(0);" class="badge badge-danger" onclick="deleteImage('<?php echo $imgRow['id']; ?>')">delete</a>
                    </div>
                <?php ?>
                </div>
            <?php ?>
        </div>
        <a href="<?php echo base_url('manage_gallery'); ?>" class="btn btn-primary">Back to List</a>
    </div>
</div>

2.3. gallery/add-edit.php
This view file is loaded by the add() and edit() functions of Manage_gallery controller.

On add request,

  • An HTML form is displayed to select multiple image files and provide the gallery name.

On edit request,

  • The data of the selected gallery will be pre-filled in the input fields and images are listed under the file upload field.
  • Delete link is provided to each uploaded image to remove the old images from the gallery.
<div class="container">
    <h1><?php echo $title?></h1>
    <hr>
    
    <!-- Display status message -->
    <?php if(!empty($error_msg)){ ?>
    <div class="col-xs-12">
        <div class="alert alert-danger"><?php echo $error_msg?></div>
    </div>
    <?php ?>
    
    <div class="row">
        <div class="col-md-6">
            <form method="post" action="" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Title:</label>
                    <input type="text" name="title" class="form-control" placeholder="Enter title" value="<?php echo !empty($gallery['title'])?$gallery['title']:''?>" >
                    <?php echo form_error('title','<p class="help-block text-danger">','</p>'); ?>
                </div>
                <div class="form-group">
                    <label>Images:</label>
                    <input type="file" name="images[]" class="form-control" multiple>
                    <?php if(!empty($gallery['images'])){ ?>
                        <div class="gallery-img">
                        <?php foreach($gallery['images'] as $imgRow){ ?>
                            <div class="img-box" id="imgb_<?php echo $imgRow['id']; ?>">
                                <img src="<?php echo base_url('uploads/images/'.$imgRow['file_name']); ?>">
                                <a href="javascript:void(0);" class="badge badge-danger" onclick="deleteImage('<?php echo $imgRow['id']; ?>')">delete</a>
                            </div>
                        <?php ?>
                        </div>
                    <?php ?>
                </div>
                
                <a href="<?php echo base_url('manage_gallery'); ?>" class="btn btn-secondary">Back</a>
                <input type="hidden" name="id" value="<?php echo !empty($gallery['id'])?$gallery['id']:''?>">
                <input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
            </form>
        </div>
    </div>
</div>

Multiple Image Upload with View, Edit and Delete in PHP

Conclusion

Our sample gallery management script with CodeIgniter helps you to integrate multiple images upload feature with the view, add, edit, and delete functionality. You can use this script for any types of data management section where multiple image upload is required. This example code is very useful for the gallery CRUD operation. You can also enhance the functionality of our CodeIgniter gallery CRUD application as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

1 Comment

  1. Puja Said...

Leave a reply

keyboard_double_arrow_up