PHP CodeIgniter 4 - CRUD Application Tutorial

In this tutorial, we will tackle about creating a CRUD (Create, Read, Edit, and Delete) Operation in PHP CodeIgniter 4. CRUD Operations is one the most common function or feature of the web applications that contains a dynamic data. Here, you will learn how to retrieve, store, update, and delete data into the Database using the PHP CodeIgniter Framework. I will be providing a simple web application source code below that contains a CRUD Opertaion.

What is CodeIgniter?

CodeIgniter is an open-source software rapid development web framework for developing or building a PHP Projects/Applications. It was built for developers to create a full-featured web applications.

Getting Started

Before we proceed to the coding part of this tutorial, Download and Install XAMPP web server first. The XAMPP web server contains a Apache HTTP Server to run our PHP Script in your local machine and MariaDB Database for storing our data.

Setting up the XAMPP

  1. Open the XAMPP's php.ini file and locate the ;extension=intl extension.
  2. Remove the (;) semicolon to enable the said extension.
  3. Lastly, open your XAMPP's Control Panel and start the Apache and MySQL Servers.

Creating the Database

  1. Open your preferred Browser such as Chrome and browse http://localhost/phpmyadmin.
  2. Create a new database naming dummy_db.
  3. Navigate the page into the SQL page and paste the provided SQL Script below for the creation of the database tables and column.
  1. CREATE TABLE `contact_details` (
  2.   `id` int(11) NOT NULL,
  3.   `firstname` varchar(200) NOT NULL,
  4.   `middlename` varchar(200) DEFAULT NULL,
  5.   `lastname` varchar(200) NOT NULL,
  6.   `gender` varchar(50) NOT NULL,
  7.   `contact` varchar(100) NOT NULL,
  8.   `email` varchar(100) NOT NULL,
  9.   `address` text NOT NULL,
  10.  
  11.  
  12. ALTER TABLE `contact_details`
  13.   ADD PRIMARY KEY (`id`);
  14.  
  15. ALTER TABLE `contact_details`
Note: Please make sure that you are connected to the internet because the source code that I will be providing uses CDNs for thr Bootstrap and other libraries for the design of the application.

Setting up the CodeIgniter

  1. Download the CodeIgniter version 4 to their official site. https://codeigniter.com/download
  2. Next, extract the CodeIgniter 4 zip file.
  3. Open your terminal or command prompt and change your directory inside the CodeIgniter 4 folder.
  4. Excecute the following command:
    • php spark server
  5. Browse the provided link into your browser to check if it works. i.e http://localhost:8080

Next, open your CodeIgniter 4 source code folder into your preferred text-editor such as Notepad++, Sublime Text, VS Code, etc.

Setting Up the Database Credentials

Open the Database.php file under the app >> Config >> directory in to your text-editor. Locate the $default variable on the file. Configure your database just like below.

  1. <?php
  2.  public $default = [
  3.     'DSN'      => '',
  4.     'hostname' => 'localhost',
  5.     'username' => 'root',
  6.     'password' => '',
  7.     'database' => 'dummy_db',
  8.     'DBDriver' => 'MySQLi',
  9.     'DBPrefix' => '',
  10.     'pConnect' => false,
  11.     'DBDebug'  => (ENVIRONMENT !== 'production'),
  12.     'charset'  => 'utf8',
  13.     'DBCollat' => 'utf8_general_ci',
  14.     'swapPre'  => '',
  15.     'encrypt'  => false,
  16.     'compress' => false,
  17.     'strictOn' => false,
  18.     'failover' => [],
  19.     'port'     => 3306,
  20. ];
  21.  
  22. ?>

Configuring the Routes

Open the Routes.php file located at the app >> Config directory. Then, configure the file just like below.

  1. <?php
  2.  
  3. namespace Config;
  4.  
  5. // Create a new instance of our RouteCollection class.
  6. $routes = Services::routes();
  7.  
  8. // Load the system's routing file first, so that the app and ENVIRONMENT
  9. // can override as needed.
  10. if (is_file(SYSTEMPATH . 'Config/Routes.php')) {
  11.     require SYSTEMPATH . 'Config/Routes.php';
  12. }
  13.  
  14. /*
  15.  * --------------------------------------------------------------------
  16.  * Router Setup
  17.  * --------------------------------------------------------------------
  18.  */
  19. $routes->setDefaultNamespace('App\Controllers');
  20. $routes->setDefaultController('Main');
  21. $routes->setDefaultMethod('index');
  22. $routes->setTranslateURIDashes(false);
  23. $routes->set404Override();
  24. // The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps
  25. // where controller filters or CSRF protection are bypassed.
  26. // If you don't want to define all routes, please use the Auto Routing (Improved).
  27. // Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
  28. //$routes->setAutoRoute(false);
  29.  
  30. /*
  31.  * --------------------------------------------------------------------
  32.  * Route Definitions
  33.  * --------------------------------------------------------------------
  34.  */
  35.  
  36. // We get a performance increase by specifying the default
  37. // route since we don't have to scan directories.
  38. $routes->get('/', 'Main::index');
  39.  
  40. $routes->get('/main/(:any)', 'Main::$1');
  41. $routes->post('/main/(:any)', 'Main::$1');
  42.  
  43. /*
  44.  * --------------------------------------------------------------------
  45.  * Additional Routing
  46.  * --------------------------------------------------------------------
  47.  *
  48.  * There will often be times that you need additional routing and you
  49.  * need it to be able to override any defaults in this file. Environment
  50.  * based routes is one such time. require() additional route files here
  51.  * to make that happen.
  52.  *
  53.  * You will have access to the $routes object within that file without
  54.  * needing to reload it.
  55.  */
  56. if (is_file(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
  57.     require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
  58. }

Creating the Model

Next, create a new model naming CrudModel.php and save the file under the app >> Models directory. Then, copy and paste the provided PHP script below and save it.

  1. <?php
  2.  
  3. namespace App\Models;
  4.  
  5. use CodeIgniter\Model;
  6.  
  7. class CrudModel extends Model
  8. {
  9.     // Table
  10.     protected $table = 'contact_details';
  11.     // allowed fields to manage
  12.     protected $allowedFields = ['firstname', 'middlename','lastname', 'gender', 'contact', 'email', 'address'];
  13. }

Creating the Interface

First, create the template files. The template files is the PHP Files that contains the script for tha main template of your application. Create a new folder naming templates under app >> Views. Then, create and save the following PHP Files.

header.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title><?= isset($page_title) ? $page_title ." | " : "" ?>CI V4 Simple Crud</title>
  8.     <!-- Styles -->
  9.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  10.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  11.     <!--end of Styles -->
  12.  
  13.     <!-- Scritps -->
  14.     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  15.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  16.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  17.     <!-- end of Scritps -->
  18.  
  19. </head>
  20. <body>
  21.     <!-- Top Navigation Bar -->
  22.     <nav class="navbar navbar-dark navbar-expand-lg bg-dark bg-gradient">
  23.         <div class="container">
  24.             <a class="navbar-brand" href="<?= base_url() ?>">CI4 Simple CRUD</a>
  25.             <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
  26.             <span class="navbar-toggler-icon"></span>
  27.             </button>
  28.             <div class="collapse navbar-collapse" id="navbarNavDropdown">
  29.                 <ul class="navbar-nav">
  30.                     <li class="nav-item">
  31.                     <a class="nav-link active" aria-current="page" href="<?= base_url() ?>">Home</a>
  32.                     </li>
  33.                     <li class="nav-item">
  34.                     <a class="nav-link" href="<?= base_url('main/create') ?>"><i class="fa fa-plus-square"></i> Add New</a>
  35.                     </li>
  36.                     <li class="nav-item">
  37.                     <a class="nav-link" href="<?= base_url('main/list') ?>"><i class="fa fa-th-list"></i> List</a>
  38.                     </li>
  39.                 </ul>
  40.             </div>
  41.             <a href="https://sourcecodester.com" target="_blank" class="text-light fw-bold text-decoration-none">SourceCodester</a>
  42.  
  43.         </div>
  44.     </nav>
  45.     <!--End Top Navigation Bar -->
  46.  
  47.     <!-- Wrapper -->
  48.     <div class="wrapper my-4">
  49.         <!-- Main Container -->
  50.         <div class="main container">
  51.             <?php if(!empty($session->getFlashdata('success_message'))): ?>
  52.                 <div class="alert alert-success rouded-0">
  53.                     <div class="d-flex">
  54.                         <div class="col-11"><?= $session->getFlashdata('success_message') ?></div>
  55.                         <div class="col-1 text-end"><a href="javascript:void(0)" onclick="$(this).closest('.alert').remove()" class="text-muted text-decoration-none"><i class="fa fa-times"></i></a></div>
  56.                     </div>
  57.                 </div>
  58.             <?php endif ?>
  59.             <?php if(!empty($session->getFlashdata('error_message'))): ?>
  60.                 <div class="alert alert-danger rouded-0">
  61.                     <div class="d-flex">
  62.                         <div class="col-11"><?= $session->getFlashdata('error_message') ?></div>
  63.                         <div class="col-1 text-end"><a href="javascript:void(0)" onclick="$(this).closest('.alert').remove()" class="text-muted text-decoration-none"><i class="fa fa-times"></i></a></div>
  64.                     </div>
  65.                 </div>
  66.             <?php endif ?>
footer.php
  1.         </div>
  2.         <!-- Main Container -->
  3.     </div>
  4.     <!--End of Wrapper -->
  5. </body>
  6. </html>

Next, create the interface of the pages of the application. Create a new folder naming crud in your app >> Views directory. Then, create and save the following PHP files.

home.php
  1. <div class="card card-outline card-primary rounded-0 mt-5">
  2.     <div class="card-body">
  3.         <div class="container-fluid">
  4.             <h1 class="text-center">Welcome to CI4 Simple CRUD Application</h1>
  5.         </div>
  6.     </div>
  7. </div>
Result Home Page list.php
  1. <div class="card card-outline card-primary rounded-0">
  2.     <div class="card-header">
  3.         <h4 class="mb-0">List of Contact</h4>
  4.     </div>
  5.     <div class="card-body">
  6.         <div class="container-fluid">
  7.             <table class="table table-stripped table-bordered">
  8.                 <colgroup>
  9.                     <col width="10%">
  10.                     <col width="40%">
  11.                     <col width="40%">
  12.                     <col width="10%">
  13.                 </colgroup>
  14.                 <thead>
  15.                     <tr class="bg-gradient bg-primary text-light">
  16.                         <th class="py-1 text-center">#</th>
  17.                         <th class="py-1 text-center">Name</th>
  18.                         <th class="py-1 text-center">Gender</th>
  19.                         <th class="py-1 text-center">Action</th>
  20.                     </tr>
  21.                 </thead>
  22.                 <tbody>
  23.                     <?php if(count($list) > 0): ?>
  24.                         <?php $i = 1; ?>
  25.                         <?php foreach($list as $row): ?>
  26.                             <tr>
  27.                                 <th class="p-1 align-middle text-center"><?= $i++ ?></th>
  28.                                 <td class="p-1 align-middle"><?= $row->lastname.", ".$row->firstname.(!empty($row->middlename)? " ".$row->middlename:'') ?></td>
  29.                                 <td class="p-1 align-middle"><?= $row->gender ?></td>
  30.                                 <td class="p-1 align-middle text-center">
  31.                                     <div class="btn-group btn-group-sm">
  32.                                         <a href="<?= base_url('main/view_details/'.$row->id) ?>" class="btn btn-default bg-gradient-light border text-dark rounded-0" title="View Contact"><i class="fa fa-eye"></i></a>
  33.                                         <a href="<?= base_url('main/edit/'.$row->id) ?>" class="btn btn-primary rounded-0" title="Edit Contact"><i class="fa fa-edit"></i></a>
  34.                                         <a href="<?= base_url('main/delete/'.$row->id) ?>" onclick="if(confirm('Are you sure to delete this contact details?') === false) event.preventDefault()" class="btn btn-danger rounded-0" title="Delete Contact"><i class="fa fa-trash"></i></a>
  35.                                     </div>
  36.                                 </td>
  37.                             </tr>
  38.                         <?php endforeach; ?>
  39.                     <?php endif; ?>
  40.                 </tbody>
  41.             </table>
  42.            
  43.         </div>
  44.     </div>
  45. </div>
Result Home Page create.php
  1. <div class="card card-primary rounded-0">
  2.     <div class="card-header">
  3.         <h4 class="text-muted"><i class="far fa-plus-square"></i> Add New Contact Details</h4>
  4.     </div>
  5.     <div class="card-body">
  6.         <div class="contianer-fluid">
  7.             <form action="<?= base_url('main/save') ?>" method="POST" id="create-form">
  8.                 <input type="hidden" name="id">
  9.                
  10.                 <div class="mb-3">
  11.                     <label for="" class="control-label">Fullname (first name, middle name, last name)</label>
  12.                     <div class="input-group">
  13.                         <input type="text" autofocus class="form-control form-control-border" id="firstname" name="firstname" value="<?= !empty($request->getPost('firstname')) ? $request->getPost('firstname') : '' ?>" required="required" placeholder="First Name">
  14.                         <input type="text" class="form-control form-control-border" id="middlename" name="middlename" value="<?= !empty($request->getPost('middlename')) ? $request->getPost('middlename') : '' ?>" required="false" placeholder="Middle Name (optional)">
  15.                         <input type="text" class="form-control form-control-border" id="lastname" name="lastname" value="<?= !empty($request->getPost('lastname')) ? $request->getPost('lastname') : '' ?>" required="required" placeholder="Last Name">
  16.                     </div>
  17.                 </div>
  18.                 <div class="mb-3 col-lg-6 col-md-6 col-sm-12 col-xs-12">
  19.                     <label for="gender" class="control-label">Gender</label>
  20.                     <select name="gender" id="gender" class="form-select form-select-border" required>
  21.                         <option <?= !empty($request->getPost('gender')) && $request->getPost('gender') == 'Male' ? 'selecte' : '' ?>>Male</option>
  22.                         <option <?= !empty($request->getPost('gender')) && $request->getPost('gender') == 'Female' ? 'selecte' : '' ?>>Female</option>
  23.                     </select>
  24.                 </div>
  25.                 <div class="mb-3">
  26.                     <div class="row">
  27.                         <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
  28.                             <label for="contact" class="control-label">Contact #</label>
  29.                             <input type="text" class="form-control" id="contact" name="contact" required="required" value="<?= !empty($request->getPost('contact')) ? $request->getPost('contact') : '' ?>">
  30.                         </div>
  31.                         <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
  32.                             <label for="email" class="control-label">Email</label>
  33.                             <input type="email" class="form-control" id="email" name="email" required="required" value="<?= !empty($request->getPost('email')) ? $request->getPost('email') : '' ?>">
  34.                         </div>
  35.                     </div>
  36.                 </div>
  37.                 <div class="mb-3 col-lg-6 col-md-6 col-sm-12 col-xs-12">
  38.                     <label for="address" class="control-label">Address</label>
  39.                     <textarea name="address" id="address" cols="30" rows="3" class="form-control" required="required"><?= !empty($request->getPost('address')) ? $request->getPost('address') : '' ?></textarea>
  40.                 </div>
  41.             </form>
  42.         </div>
  43.     </div>
  44.     <div class="card-footer text-center">
  45.         <button class="btn btn-primary" form="create-form" type="submit"><i class="fa fa-save"></i> Save Details</button>
  46.         <button class="btn btn-secondary" form="create-form" type="reset"><i class="fa fa-times"></i> Reset</button>
  47.     </div>
  48. </div>
Result Home Page view.php
  1. <div class="card card-outline card-primary rounded-0">
  2.     <div class="card-header">
  3.         <div class="h4 mb-0">Contact Details</div>
  4.     </div>
  5.     <div class="card-body">
  6.         <div class="container-fluid">
  7.             <dl>
  8.                 <dt class="text-muted">Name</dt>
  9.                 <dd class="ps-4"><?= isset($data['name']) ? $data['name'] : '' ?></dd>
  10.                 <dt class="text-muted">Gender</dt>
  11.                 <dd class="ps-4"><?= isset($data['gender']) ? $data['gender'] : '' ?></dd>
  12.                 <dt class="text-muted">Contact #</dt>
  13.                 <dd class="ps-4"><?= isset($data['contact']) ? $data['contact'] : '' ?></dd>
  14.                 <dt class="text-muted">Email</dt>
  15.                 <dd class="ps-4"><?= isset($data['email']) ? $data['email'] : '' ?></dd>
  16.                 <dt class="text-muted">Address</dt>
  17.                 <dd class="ps-4"><?= isset($data['address']) ? $data['address'] : '' ?></dd>
  18.             </dl>
  19.         </div>
  20.     </div>
  21.     <div class="card-footer text-center">
  22.             <a href="<?= base_url('main/edit/'.(isset($data['id']) ? $data['id'] : '')) ?>" class="btn btn btn-primary btn-sm rounded-0"><i class="fa fa-edit"></i> Edit</a>
  23.             <a href="<?= base_url('main/delete/'.(isset($data['id']) ? $data['id'] : '')) ?>" class="btn btn btn-danger btn-sm rounded-0" onclick="if(confirm('Are you sure to delete this contact details?') === false) event.preventDefault()"><i class="fa fa-trash"></i> Delete</a>
  24.             <a href="<?= base_url('main/list') ?>" class="btn btn btn-light bg-gradient-light border btn-sm rounded-0"><i class="fa fa-angle-left"></i> Back to List</a>
  25.     </div>
  26. </div>
Result Home Page edit.php
  1. <div class="card card-primary rounded-0">
  2.     <div class="card-header">
  3.         <h4 class="text-muted"><i class="far fa-edit"></i> Edit Contact Details</h4>
  4.     </div>
  5.     <div class="card-body">
  6.         <div class="contianer-fluid">
  7.             <form action="<?= base_url('main/save') ?>" method="POST" id="create-form">
  8.                 <input type="hidden" name="id" value="<?= isset($data['id']) ? $data['id'] : '' ?>">
  9.                 <div class="mb-3">
  10.                     <label for="" class="control-label">Fullname (first name, middle name, last name)</label>
  11.                     <div class="input-group">
  12.                         <input type="text" autofocus class="form-control form-control-border" id="firstname" name="firstname" value="<?= isset($data['firstname']) ? $data['firstname'] : '' ?>" required="required" placeholder="First Name">
  13.                         <input type="text" class="form-control form-control-border" id="middlename" name="middlename" value="<?= isset($data['middlename']) ? $data['middlename'] : '' ?>" required="false" placeholder="Middle Name (optional)">
  14.                         <input type="text" class="form-control form-control-border" id="lastname" name="lastname" value="<?= isset($data['lastname']) ? $data['lastname'] : '' ?>" required="required" placeholder="Last Name">
  15.                     </div>
  16.                 </div>
  17.                 <div class="mb-3 col-lg-6 col-md-6 col-sm-12 col-xs-12">
  18.                     <label for="gender" class="control-label">Gender</label>
  19.                     <select name="gender" id="gender" class="form-select form-select-border" required>
  20.                         <option <?= isset($data['gender']) && $data['gender'] == 'Male' ? 'selecte' : '' ?>>Male</option>
  21.                         <option <?= isset($data['gender']) && $data['gender'] == 'Female' ? 'selecte' : '' ?>>Female</option>
  22.                     </select>
  23.                 </div>
  24.                 <div class="mb-3">
  25.                     <div class="row">
  26.                         <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
  27.                             <label for="contact" class="control-label">Contact #</label>
  28.                             <input type="text" class="form-control" id="contact" name="contact" required="required" value="<?= isset($data['contact']) ? $data['contact'] : '' ?>">
  29.                         </div>
  30.                         <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
  31.                             <label for="email" class="control-label">Email</label>
  32.                             <input type="email" class="form-control" id="email" name="email" required="required" value="<?= isset($data['email']) ? $data['email'] : '' ?>">
  33.                         </div>
  34.                     </div>
  35.                 </div>
  36.                 <div class="mb-3 col-lg-6 col-md-6 col-sm-12 col-xs-12">
  37.                     <label for="address" class="control-label">Address</label>
  38.                     <textarea name="address" id="address" cols="30" rows="3" class="form-control" required="required"><?= isset($data['address']) ? $data['address'] : '' ?></textarea>
  39.                 </div>
  40.             </form>
  41.         </div>
  42.     </div>
  43.     <div class="card-footer text-center">
  44.         <button class="btn btn-primary" form="create-form" type="submit"><i class="fa fa-save"></i> Save Details</button>
  45.         <a class="btn btn-secondary" href="<?= base_url('main/view_details/'.(isset($data['id']) ? $data['id'] : '')) ?>"><i class="fa fa-times"></i> Cancel</a>
  46.     </div>
  47. </div>
Result Home Page

Creating the Controller

Lastly, we will create the Main Controller to our application. The controller file contain the files that processes the CRUD Operations and display our pages.On your app >> Controllers directory, create a new PHP file naming Main.php. Then, paste the following PHP Script.

  1. <?php
  2.  
  3. namespace App\Controllers;
  4.  
  5. use App\Models\CrudModel;
  6.  
  7. class Main extends BaseController
  8. {
  9.     // Session
  10.     protected $session;
  11.     // Data
  12.     protected $data;
  13.     // Model
  14.     protected $crud_model;
  15.  
  16.     // Initialize Objects
  17.     public function __construct(){
  18.         $this->crud_model = new CrudModel();
  19.         $this->session= \Config\Services::session();
  20.         $this->data['session'] = $this->session;
  21.     }
  22.  
  23.     // Home Page
  24.     public function index(){
  25.         $this->data['page_title'] = "Home Page";
  26.         echo view('templates/header', $this->data);
  27.         echo view('crud/home', $this->data);
  28.         echo view('templates/footer');
  29.     }
  30.  
  31.     // Create Form Page
  32.     public function create(){
  33.         $this->data['page_title'] = "Add New";
  34.         $this->data['request'] = $this->request;
  35.         echo view('templates/header', $this->data);
  36.         echo view('crud/create', $this->data);
  37.         echo view('templates/footer');
  38.     }
  39.  
  40.     // Insert And Update Function
  41.     public function save(){
  42.         $this->data['request'] = $this->request;
  43.         $post = [
  44.             'firstname' => $this->request->getPost('firstname'),
  45.             'middlename' => $this->request->getPost('middlename'),
  46.             'lastname' => $this->request->getPost('lastname'),
  47.             'gender' => $this->request->getPost('gender'),
  48.             'contact' => $this->request->getPost('contact'),
  49.             'email' => $this->request->getPost('email'),
  50.             'address' => $this->request->getPost('address')
  51.         ];
  52.         if(!empty($this->request->getPost('id')))
  53.             $save = $this->crud_model->where(['id'=>$this->request->getPost('id')])->set($post)->update();
  54.         else
  55.             $save = $this->crud_model->insert($post);
  56.         if($save){
  57.             if(!empty($this->request->getPost('id')))
  58.             $this->session->setFlashdata('success_message','Data has been updated successfully') ;
  59.             else
  60.             $this->session->setFlashdata('success_message','Data has been added successfully') ;
  61.             $id =!empty($this->request->getPost('id')) ? $this->request->getPost('id') : $save;
  62.             return redirect()->to('/main/view_details/'.$id);
  63.         }else{
  64.             echo view('templates/header', $this->data);
  65.             echo view('crud/create', $this->data);
  66.             echo view('templates/footer');
  67.         }
  68.     }
  69.  
  70.     // List Page
  71.     public function list(){
  72.         $this->data['page_title'] = "List of Contacts";
  73.         $this->data['list'] = $this->crud_model->orderBy('date(date_created) ASC')->select('*')->get()->getResult();
  74.         echo view('templates/header', $this->data);
  75.         echo view('crud/list', $this->data);
  76.         echo view('templates/footer');
  77.     }
  78.  
  79.     // Edit Form Page
  80.     public function edit($id=''){
  81.         if(empty($id)){
  82.             $this->session->setFlashdata('error_message','Unknown Data ID.') ;
  83.             return redirect()->to('/main/list');
  84.         }
  85.         $this->data['page_title'] = "Edit Contact Details";
  86.         $qry= $this->crud_model->select('*')->where(['id'=>$id]);
  87.         $this->data['data'] = $qry->first();
  88.         echo view('templates/header', $this->data);
  89.         echo view('crud/edit', $this->data);
  90.         echo view('templates/footer');
  91.     }
  92.  
  93.     // Delete Data
  94.     public function delete($id=''){
  95.         if(empty($id)){
  96.             $this->session->setFlashdata('error_message','Unknown Data ID.') ;
  97.             return redirect()->to('/main/list');
  98.         }
  99.         $delete = $this->crud_model->delete($id);
  100.         if($delete){
  101.             $this->session->setFlashdata('success_message','Contact Details has been deleted successfully.') ;
  102.             return redirect()->to('/main/list');
  103.         }
  104.     }
  105.  
  106.     // View Data
  107.     public function view_details($id=''){
  108.         if(empty($id)){
  109.             $this->session->setFlashdata('error_message','Unknown Data ID.') ;
  110.             return redirect()->to('/main/list');
  111.         }
  112.         $this->data['page_title'] = "View Contact Details";
  113.         $qry= $this->crud_model->select("*, CONCAT(lastname,', ',firstname,COALESCE(concat(' ', middlename), '')) as `name`")->where(['id'=>$id]);
  114.         $this->data['data'] = $qry->first();
  115.         echo view('templates/header', $this->data);
  116.         echo view('crud/view', $this->data);
  117.         echo view('templates/footer');
  118.     }
  119.    
  120. }

That's it! You can now test the source code and see if it meets our goal for this tutorial which is to have a Simple Application with CRUD Operation using the PHP CodeIgniter 4 Framework. If there's an error occurred on your end please review the changes in your source code and differentiate it from the source code I provided above. you can also download the working source code I created for this tutorial. The dowload button is located below this article.

DEMO VIDEO

That's the end of this tutorial. I hope this will help you with what you are looking for and you'll find this useful for your future PHP Projects using CodeIgniter 4 Framework. Explore more on this website for more Tutorials and Free Source Codes.

Enjoy Coding :)

Add new comment