YouTube Icon

Code Playground.

How to develop Image Gallery CRUD in CodeIgniter

CFG

How to develop Image Gallery CRUD in CodeIgniter

CRUD operations are the most used functionality for the CodeIgniter application. CodeIgniter CRUD functionality helps to implement the view, add, edit, and delete operations in the web application. Generally, the CRUD functionality is used to manage data with the database. Not only the data management but also the image file upload functionality can be managed with CRUD.

The image files management system is useful to integrate a dynamic image gallery in the web application. Image Gallery CRUD helps to manage images and control the visibility of the images in the gallery. It very useful when you want to provide an admin interface to manage the image files of the gallery. In this tutorial, we will show you how to create a dynamic image gallery and manage image files (upload, view, edit, and delete) in CodeIgniter with MySQL database.

In the sample CodeIgniter application, we will implement an image gallery CRUD with the database in the CodeIgniter framework.

  • Fetch the images data from the database and listed on the web page.
  • Upload image and add data to the database.
  • Edit and update image data in the database.
  • Delete image data from the database.
  • Dynamic image gallery with lightbox.

Before getting started to integrate Image Gallery CRUD in CodeIgniter, take a look at the files structure.

Create Database Table

To store the file information of the images a table is required in the database. The following SQL creates an images table with some basic fields in the MySQL database.

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `file_name` 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;

Config

autoload.php
In the config/autoload.php file, define the library and helper which will be used frequently in the application.

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

Controllers

Gallery.php
The Gallery controller helps to display the images in a gallery view.

  • __construct() –
    • Load the Image model.
    • Define default controller name.
  • index() –
    • Fetch the records from the database using getRows() method of the Image model.
    • Pass the images data and load the gallery view.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
 
class Gallery extends CI_Controller { 
     
    function __construct() { 
        parent::__construct(); 
         
        // Load image model 
        $this->load->model('image'); 
         
        // Default controller name 
        $this->controller = 'gallery'; 
    } 
     
    public function index(){ 
        $data = array(); 
         
        $con = array( 
            'where'=> array( 
                'status' => 1 
            ) 
        ); 
        $data['gallery'] = $this->image->getRows($con); 
        $data['title'] = 'Images Gallery'; 
         
        // Load the list page view 
        $this->load->view('templates/header', $data); 
        $this->load->view('gallery/index', $data); 
        $this->load->view('templates/footer'); 
    } 
}

Manage_gallery.php
The Manage_gallery controller handles the CRUD operations (view, add, edit, and delete) of the image files and data.

  • __construct() –
    • Load the form helper and validation library.
    • Load the Image model.
    • Define default controller name.
  • index() –
    • Retrieve status messages from SESSION.
    • Fetch the records from the database using getRows() method of the Image model.
    • Pass the images data and load the list view.
  • view() –
    • Fetch the image information from the database based on the specific ID.
    • Pass the image data and load the details view.
  • add() –
    • Initially, the form view is loaded to receive input of the image title and file.
    • If the form is submitted,
      • The posted form data is validated using CodeIgniter Form Validation library.
      • Upload the selected image file to the server using CodeIgniter Upload library.
      • Insert uploaded file information and image title in the database using insert() method of the Image model.
    • Pass the status to the image upload view.
  • edit() –
    • Fetch the image data from the database based on the specific ID.
    • The form view is loaded with pre-filled image data.
    • If the form is submitted,
      • The posted form data is validated using CodeIgniter Form Validation library.
      • Upload selected image to the server using CodeIgniter Upload library.
      • Update image data in the database using update() method of the Image model.
  • block() – Update the status of the image to Inactive.
  • unblock() – Update the status of the image to Active.
  • delete() –
    • Remove image data from the database using delete() method of the Image model.
    • Remove the image file from the server.
  • file_check() – Custom callback function to validate image upload field value.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
 
class Manage_gallery extends CI_Controller { 
     
    function __construct() { 
        parent::__construct(); 
         
        // Load image model 
        $this->load->model('image'); 
         
        $this->load->helper('form'); 
        $this->load->library('form_validation'); 
         
        // Default controller name 
        $this->controller = 'manage_gallery'; 
         
        // File upload path 
        $this->uploadPath = 'uploads/images/'; 
    } 
     
    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->image->getRows(); 
        $data['title'] = 'Images Archive'; 
         
        // Load the list page view 
        $this->load->view('templates/header', $data); 
        $this->load->view($this->controller.'/index', $data); 
        $this->load->view('templates/footer'); 
    } 
     
    public function view($id){ 
        $data = array(); 
         
        // Check whether id is not empty 
        if(!empty($id)){ 
            $con = array('id' => $id); 
            $data['image'] = $this->image->getRows($con); 
            $data['title'] = $data['image']['title']; 
             
            // Load the details page view 
            $this->load->view('templates/header', $data); 
            $this->load->view($this->controller.'/view', $data); 
            $this->load->view('templates/footer'); 
        }else{ 
            redirect($this->controller); 
        } 
    } 
     
    public function add(){ 
        $data = $imgData = array(); 
        $error = ''; 
         
        // If add request is submitted 
        if($this->input->post('imgSubmit')){ 
            // Form field validation rules 
            $this->form_validation->set_rules('title', 'image title', 'required'); 
            $this->form_validation->set_rules('image', 'image file', 'callback_file_check'); 
             
            // Prepare gallery data 
            $imgData = array( 
                'title' => $this->input->post('title') 
            ); 
             
            // Validate submitted form data 
            if($this->form_validation->run() == true){ 
                // Upload image file to the server 
                if(!empty($_FILES['image']['name'])){ 
                    $imageName = $_FILES['image']['name']; 
                     
                    // File upload configuration 
                    $config['upload_path'] = $this->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('image')){ 
                        // Uploaded file data 
                        $fileData = $this->upload->data(); 
                        $imgData['file_name'] = $fileData['file_name']; 
                    }else{ 
                        $error = $this->upload->display_errors();  
                    } 
                } 
                 
                if(empty($error)){ 
                    // Insert image data 
                    $insert = $this->image->insert($imgData); 
                     
                    if($insert){ 
                        $this->session->set_userdata('success_msg', 'Image has been uploaded successfully.'); 
                        redirect($this->controller); 
                    }else{ 
                        $error = 'Some problems occurred, please try again.'; 
                    } 
                } 
                 
                $data['error_msg'] = $error; 
            } 
        } 
         
        $data['image'] = $imgData; 
        $data['title'] = 'Upload Image'; 
        $data['action'] = 'Upload'; 
         
        // Load the add page view 
        $this->load->view('templates/header', $data); 
        $this->load->view($this->controller.'/add-edit', $data); 
        $this->load->view('templates/footer'); 
    } 
     
    public function edit($id){ 
        $data = $imgData = array(); 
         
        // Get image data 
        $con = array('id' => $id); 
        $imgData = $this->image->getRows($con); 
        $prevImage = $imgData['file_name']; 
         
        // 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 
            $imgData = array( 
                'title' => $this->input->post('title') 
            ); 
             
            // Validate submitted form data 
            if($this->form_validation->run() == true){ 
                // Upload image file to the server 
                if(!empty($_FILES['image']['name'])){ 
                    $imageName = $_FILES['image']['name']; 
                     
                    // File upload configuration 
                    $config['upload_path'] = $this->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('image')){ 
                        // Uploaded file data 
                        $fileData = $this->upload->data(); 
                        $imgData['file_name'] = $fileData['file_name']; 
                         
                        // Remove old file from the server  
                        if(!empty($prevImage)){ 
                            @unlink($this->uploadPath.$prevImage);  
                        } 
                    }else{ 
                        $error = $this->upload->display_errors();  
                    } 
                } 
                 
                if(empty($error)){ 
                    // Update image data 
                    $update = $this->image->update($imgData, $id); 
                     
                    if($update){ 
                        $this->session->set_userdata('success_msg', 'Image has been updated successfully.'); 
                        redirect($this->controller); 
                    }else{ 
                        $error = 'Some problems occurred, please try again.'; 
                    } 
                } 
                 
                $data['error_msg'] = $error; 
            } 
        } 
 
         
        $data['image'] = $imgData; 
        $data['title'] = 'Update Image'; 
        $data['action'] = 'Edit'; 
         
        // Load the edit page view 
        $this->load->view('templates/header', $data); 
        $this->load->view($this->controller.'/add-edit', $data); 
        $this->load->view('templates/footer'); 
    } 
     
    public function block($id){ 
        // Check whether id is not empty 
        if($id){ 
            // Update image status 
            $data = array('status' => 0); 
            $update = $this->image->update($data, $id); 
             
            if($update){ 
                $this->session->set_userdata('success_msg', 'Image 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 is not empty 
        if($id){ 
            // Update image status 
            $data = array('status' => 1); 
            $update = $this->image->update($data, $id); 
             
            if($update){ 
                $this->session->set_userdata('success_msg', 'Image 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){ 
            $con = array('id' => $id); 
            $imgData = $this->image->getRows($con); 
             
            // Delete gallery data 
            $delete = $this->image->delete($id); 
             
            if($delete){ 
                // Remove file from the server  
                if(!empty($imgData['file_name'])){ 
                    @unlink($this->uploadPath.$imgData['file_name']);  
                }  
                 
                $this->session->set_userdata('success_msg', 'Image has been removed successfully.'); 
            }else{ 
                $this->session->set_userdata('error_msg', 'Some problems occurred, please try again.'); 
            } 
        } 
 
        redirect($this->controller); 
    } 
     
    public function file_check($str){ 
        if(empty($_FILES['image']['name'])){ 
            $this->form_validation->set_message('file_check', 'Select an image file to upload.'); 
            return FALSE; 
        }else{ 
            return TRUE; 
        } 
    } 
}

Model (Image.php)

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

  • __construct() – Define the table name.
  • getRows() – Fetch the images data from the database based on the specified parameters passed in the $params. Returns the data array on success, and FALSE on error.
  • insert() – Insert image data in the database. Returns the row ID on success, and FALSE on error.
  • update() – Update image 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.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
 
class Image extends CI_Model{ 
     
    function __construct() { 
        $this->table = 'images'; 
    } 
     
    /* 
     * Returns rows from the database based on the conditions 
     * @param array filter data based on the passed parameters 
     */ 
    public function getRows($params = array()){ 
        $this->db->select('*'); 
        $this->db->from($this->table); 
         
        if(array_key_exists("where", $params)){ 
            foreach($params['where'] as $key => $val){ 
                $this->db->where($key, $val); 
            } 
        } 
         
        if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){ 
            $result = $this->db->count_all_results(); 
        }else{ 
            if(array_key_exists("id", $params)){ 
                $this->db->where('id', $params['id']); 
                $query = $this->db->get(); 
                $result = $query->row_array(); 
            }else{ 
                $this->db->order_by('created', 'desc'); 
                if(array_key_exists("start",$params) && array_key_exists("limit",$params)){ 
                    $this->db->limit($params['limit'],$params['start']); 
                }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){ 
                    $this->db->limit($params['limit']); 
                } 
                 
                $query = $this->db->get(); 
                $result = ($query->num_rows() > 0)?$query->result_array():FALSE; 
            } 
        } 
         
        // Return fetched data 
        return $result; 
    } 
     
    /* 
     * Insert image 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 member data 
            $insert = $this->db->insert($this->table, $data); 
             
            // Return the status 
            return $insert?$this->db->insert_id():false; 
        } 
        return false; 
    } 
     
    /* 
     * Update image 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 member data 
            $update = $this->db->update($this->table, $data, array('id' => $id)); 
             
            // Return the status 
            return $update?true:false; 
        } 
        return false; 
    } 
     
    /* 
     * Delete image data from the database 
     * @param num filter data based on the passed parameter 
     */ 
    public function delete($id){ 
        // Delete member data 
        $delete = $this->db->delete($this->table, array('id' => $id)); 
         
        // Return the status 
        return $delete?true:false; 
    } 
     
}

Views

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

1.1. templates/header.php
The header.php file holds the header part 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). Also, other required, JS or CSS library files can be included in this view element.

<!DOCTYPE html>
<html lang="en-US">
<head>
<title><?php echo $title; ?> | Gallery CRUD in CodeIgniter</title>
<meta charset="utf-8">

<!-- Bootstrap library -->
<link rel="stylesheet" href="<?php echo base_url('assets/bootstrap/bootstrap.min.css'); ?>">

<!-- Stylesheet file -->
<link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>">

<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
</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 Gallery controller.

2.1. gallery/index.php
Initially, all the images are retrieved from the database and listed in a gallery view with lightbox popup.

  • The jQuery fancyBox plugin is used to show the image gallery on the popup. So, include the CSS and JS library of the fancyBox plugin.
  • Call the fancybox() method and specify a selector to bind the fancyBox event in the image gallery.
  • Specify data-fancybox="gallery" and data-caption attributes in the anchor tag of the images to enable the fancyBox popup.
  • Specify the large image file path in the href attribute.
<div class="container">
    <h2>Gallery Images</h2>
    <hr>
    <div class="head">
        <a href="<?php echo base_url('manage_gallery/'); ?>" class="glink">Manage</a>
    </div>
    <div class="gallery">
        <?php if(!empty($gallery)){ ?> 
        <?php 
            foreach($gallery as $row){ 
                $uploadDir = base_url().'uploads/images/'; 
                $imageURL = $uploadDir.$row["file_name"]; 
        ?>
        <div class="col-lg-3">
            <a href="<?php echo $imageURL; ?>" data-fancybox="gallery" data-caption="<?php echo $row["title"]; ?>" >
                <img src="<?php echo $imageURL; ?>" alt="" />
                <p><?php echo $row["title"]; ?></p>
            </a>
        </div>
        <?php } ?> 
        <?php }else{ ?>
            <div class="col-xs-12">
                <div class="alert alert-danger">No image(s) found...</div>
            </div>
        <?php } ?>
    </div>
</div>

<!-- Fancybox CSS library -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/fancybox/jquery.fancybox.css'); ?>">

<!-- Fancybox JS library -->
<script src="<?php echo base_url('assets/fancybox/jquery.fancybox.js'); ?>"></script>

<!-- Initialize fancybox -->
<script>
    $("[data-fancybox]").fancybox();
</script>

3. manage_gallery/
The views/manage_gallery/ directory holds the view files of the Manage_gallery controller.

3.1. manage_gallery/index.php
Initially, all the images data is retrieved from the database and listed in a tabular view with the Upload, Edit, and Delete options.

  • The View link displays the selected image info.
  • The Upload link allows adding image title and upload file.
  • The Edit link allows to edit and update image info.
  • The Delete link allows deleting image from the database.
  • The Status badge (Active/Inactive) allows controlling the visibility of the image in the gallery.
<div class="container">
    <h2>Gallery 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> Upload Image</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++; 
                        $image = !empty($row['file_name'])?'<img src="'.base_url().'uploads/images/'.$row['file_name'].'" 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 $image; ?></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 image(s) found...</td></tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
</div>

3.2. manage_gallery/view.php
This view file is loaded by the view() method of Manage_gallery controller. The selected image details are displayed on the webpage.

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h5><?php echo !empty($image['title'])?$image['title']:''; ?></h5>
            <?php if(!empty($image['file_name'])){ ?>
                <div class="img-box">
                    <img src="<?php echo base_url('uploads/images/'.$image['file_name']); ?>">
                </div>
            <?php } ?>
        </div>
        <a href="<?php echo base_url('manage_gallery'); ?>" class="btn btn-primary">Back to List</a>
    </div>
</div>

3.3. manage_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 an image file and provide the title.
  • On edit request, the data of the selected image will be pre-filled in the input fields and preview of the image is displayed under the file upload field.
<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($image['title'])?$image['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="image" class="form-control" multiple>
                    <?php echo form_error('image','<p class="help-block text-danger">','</p>'); ?>
                    <?php if(!empty($image['file_name'])){ ?>
                        <div class="img-box">
                            <img src="<?php echo base_url('uploads/images/'.$image['file_name']); ?>">
                        </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($image['id'])?$image['id']:''; ?>">
                <input type="submit" name="imgSubmit" class="btn btn-success" value="SUBMIT">
            </form>
        </div>
    </div>
</div>

Conclusion

This sample gallery CRUD helps you to integrate images upload and management functionality in the website. It allows you to create a dynamic image gallery with lightbox popup (fancyBox) in CodeIgniter application. Use this image gallery CRUD to manage the images of the gallery. You can easily enhance the functionality of this CodeIgniter photo gallery management system as per your needs.




CFG