Skip to Content
PHPCODE
Image gallery in CodeIgniter
php code / September 18, 2021

The most commonly used capability in the CodeIgniter application is CRUD operations. The CRUD capability in CodeIgniter aids in the implementation of view, add, edit, and delete activities in a web application. The CRUD functionality is typically used to maintain data in a database. With CRUD, you can control not just your data, but also your picture file upload functionality.

A dynamic image gallery can be integrated into a web application using the image files management system. Image Gallery CRUD aids in the management of photographs and the control of their visibility in the gallery. It comes in handy when you need to provide an admin interface for managing the gallery’s image files. In this tutorial, we’ll teach you how to use CodeIgniter and MySQL to develop a dynamic image gallery and handle image files (upload, view, edit, and remove).

We will implement an image gallery CRUD with the database in the CodeIgniter framework in the sample CodeIgniter application.

Obtain image data from the database and display it on the web page.
Add data to the database and upload an image.
In the database, edit and update image data.
Delete the database’s picture data.
With a lightbox, this is a dynamic image gallery.
Take a look at the file structure before starting to integrate Image Gallery CRUD in CodeIgniter.

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

Make a database table.
A table in the database is required to store the image file information. In the MySQL database, the following SQL creates a pictures table with some basic fields.

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
Define the library and helper that will be used frequently in the application in the config/autoload.php file.

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

Controllers Gallery.php
The Gallery controller assists in the presentation of photographs in a gallery view.

Load the Image model with __construct().
Set the name of the default controller.
index() – Using the Image model’s getRows() method, fetch records from the database.
Load the gallery display after passing the image data.

<?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 is in charge of the picture files and data CRUD actions (view, add, edit, and remove).

__construct() – Load the validation and form helper libraries.
Load the Image model into the scene.
Set the name of the default controller.
SESSION status messages are retrieved using index().
Using the Image model’s getRows() method, retrieve the records from the database.
Load the list view after passing the picture data.
view() – Retrieves image data from the database based on a unique ID.
Load the details view after passing the picture data.

 

add() – The form view is initially loaded to receive picture title and file input.

If you fill out the form and submit it, you will receive a confirmation email.

The CodeIgniter Form Validation library is used to validate the data from the submitted form.

Using the CodeIgniter Upload library, upload the desired image file to the server.

Using the Image model’s insert() method, save uploaded file details and image title in the database.

The status is passed to the image upload view.

edit() is a function that allows you to make changes to your text

Using the relevant ID, retrieve image data from the database.

The pre-filled picture data is loaded into the form view.

If you fill out the form and submit it, you will receive a confirmation email.

The CodeIgniter Form Validation library is used to validate the data from the submitted form.
Using the CodeIgniter Upload library, upload a specified image to the server.
The update() method of the Image model is used to update image data in the database.
block() – Sets the image’s status to Inactive.
unblock() – Sets the image’s state to Active.
delete() – The delete() method of the Image model is used to remove image data from the database.
The image file should be removed from the server.
file check() – A custom callback function for validating the validity of an image upload field.

<?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; 
} 
} 
}

Modeling (Image.php)
The database operations are handled by the Image model (Fetch, Add, Edit, and Delete).

Define the table name with __construct().
getRows() – Gets the pictures data from the database using the parameters supplied in the $params parameter. If successful, returns the data array; if unsuccessful, returns FALSE.
Insert image data into the database with insert(). If successful, returns the row ID; if unsuccessful, returns FALSE.
update() – Using the row ID, update picture data in the database. If the function succeeds, it returns TRUE; if it fails, it returns FALSE.
remove() – Using the row ID, delete a record from the database. If the function succeeds, it returns TRUE; if it fails, it returns FALSE.

<?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; 
} 
}

1. templates/ The views/templates/ directory contains the web page’s element sections (header, footer, etc.).

templates/header.php (version 1.1)
The header.php file contains the web page’s header. The HTML table and form are styled with the Bootstrap 4 library. As a result, include the Bootstrap library’s CSS file as well as the custom stylesheet file (if any). This view element can also contain other essential JS or CSS library files.

<!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>

templates/footer.php (1.2)
This file contains the web page’s footer area.

</body>
</html>

The views/gallery/ directory contains the Gallery controller’s view files.

gallery/index.php (version 2.1)
The photographs are first downloaded from the database and shown in a gallery view with a lightbox popup.

The image gallery on the popup is displayed using the jQuery fancyBox plugin. As a result, include the fancyBox plugin’s CSS and JS libraries.
To bind the fancyBox event in the image gallery, use the fancybox() method and supply a selector.
To enable the fancyBox popup, add the data-fancybox=”gallery” and data-caption attributes to the anchor tag of the images.
In the href attribute, specify the location of the huge picture file.

<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 Manage gallery controller’s view files are located in the views/manage gallery/ directory.

manage gallery/index.php (version 3.1)
Initially, all of the photos data is retrieved from the database and displayed in a tabular view with options to Upload, Edit, and Delete.

The View button shows the information about the image you’ve chosen.
The Upload button allows you to give your image a title and upload a file.
Editing and updating image information is possible using the Edit link.
The Delete button allows you to remove an image from the database.
The image’s appearance in the gallery can be controlled using the Status badge (Active/Inactive).

<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>

manage gallery/view.php
The view() method of the Manage gallery controller loads this view file. On the webpage, the details of the selected photograph are displayed.

<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>

manage gallery/add-edit.php (version 3.3)
The Manage gallery controller’s add() and edit() procedures load this view file.

An HTML form appears when an add request is made, allowing you to select an image file and enter a title.
On an update request, the data from the selected image is pre-filled in the input forms, and a preview of the image appears beneath 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>

Note :

This sample gallery CRUD will assist you in incorporating picture upload and management features into your website. In a CodeIgniter application, it allows you to construct a dynamic image gallery with a lightbox popup (fancyBox). To manage the gallery’s images, use this image gallery CRUD. You may easily customise this CodeIgniter photo gallery management system to meet your specific requirements.

PHPCODE © 2024