Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is CRUD 
3.
CRUD in CodeIgniter
3.1.
Requirements
4.
Setup of CodeIgniter 
5.
Working with the Controller Class
6.
Working with Model Class
7.
Creating Routes for the Application
8.
Creating Views
8.1.
listname.php
8.2.
insertname.php
8.3.
editname.php
9.
Frequently Asked Questions
9.1.
Why do we use a PHP framework?
9.2.
Is PHP front end or back end?
9.3.
Is PHP Hard to Learn? 
9.4.
What is better, PHP or Python?
9.5.
Should I learn PHP or NodeJS?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

CRUD in codeigniter

Author Amit Singh
0 upvote

Introduction

Have you ever worked in PHP, a top-notch scripting language for the server side? Have you used any PHP framework for boosting an application's performance?

logo

This article focuses on PHP's framework, CodeIgniter. We will study CRUD in CodeIgniter in detail. We will try to understand it with a proper example. Let's see all these things in more detail.

Also read about, Interpolation in Angular

What is CRUD 

The acronym CRUD means Create, Read, Update, and Delete. Any application that uses persistent data must have CRUD operations. The CRUD is an important thing that developers keep in mind when building entirely usable application models. 

Let's take the MySQL table as an example.

  • Create: It means adding new data to the table. You must be able to create new fields in the table.
     
  • Read: It refers to the ability to see the data inside the table. You must be able to read the data present in the table.
     
  • Update: It refers to the ability to change the data in case of need. You must be able to update the already present data in the table.
     
  • Delete: It refers to the ability to delete the data in the table in case of need. You must be able to delete the data present inside the table as well.

CRUD in CodeIgniter

A CodeIgniter CRUD application uses forms to insert and remove data from the databases. In this article, we'll use CodeIgniter version 4 and MySQL database to create a complete CRUD application.

The four fundamental operations are Create, Read, Update, and Delete, or CRUD. We may presume that every coder has dealt with CRUD at some point because it is a feature in most applications.

Requirements

  1. You must have a text editor.
     
  2. You must have Composer running on your computer.
     
  3. You must have a Basic Understanding of CodeIgniter.

Setup of CodeIgniter 

Before you start working on the project, you must set up the CodeIgniter in the System. We will name the project "CodeIgniter-crud-basic ."We will create the project using the following command.

composer create-project codeigniter4/appstarter CodeIgniter-crud-basic


The above instruction will download a copy of a CodeIgniter application on the Desktop. The folder name will be "CodeIgniter-crud-basic ." Using the command for the first time might take some time, depending on the internet connection.

We have to work on the "XAMPP Application," so open the XAMPP Control Panel. Click on "start" to initiate the MySQL and Apache Server.

output

Once the Apache Server and MySQL start running, open any browser(e.g., Chrome). Type "localhost/phpmyadmin" in the search bar to open the phpMyAdmin. We will use the phpMyAdmin page for the creation of the database that we will use in our application.

Once the page loading has been completed, click the "new" button. It will create a new database.

Now, type the name of the database and click on the create button. We have named it "codeigniter-crud-database."

database

After the creation of the database, you have to create a table. We will create the table using the following query.

CREATE TABLE names (
    id int(1) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(50) NOT NULL COMMENT 'Name',
    email varchar(200) NOT NULL COMMENT 'Email ID',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
INSERT INTO `names` (`id`, `name`, `email`) VALUES
(1, 'ashish', 'ashishsharma@gmail.com'),
(2, 'aditi', 'aditi@gmail.com'),
(3, 'chetanya', 'chetanya@gmail.com'),
(4, 'priyanshu', 'priyanshu@gmail.com'),
(5, 'pranav', 'pranav@gmail.com'),
(6, 'sarthak', 'sarthak@gmail.com'),
(7, 'amit', 'amit@gmail.com');
table

Once it is done, open the terminal in the "CodeIgniter-crud-basic" folder. You can type "code ." in the terminal to open the project in VS Code. 

Now, open the "CodeIgniter-crud-basic\app\Config\Database.php" file in VS Code. Now, enter the following code.

<?php namespace Config;


/**
 * Database Configuration for the crud codeigniter Project
 *
 * @package Config
 */


class Database extends \CodeIgniter\Database\Config
{
    /**
     * The directory that holds the Migrations
     * and Seeds directories.
     *
     * @var string
     */
    public $filesPath = APPPATH . 'Database/';


    /**
     * Lets you choose which connection group to
     * use if no other is specified.
     *
     * @var string
     */
    public $defaultGroup = 'default';


    /**
     * The default database connection.
     *
     * @var array
     */
    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter-crud-database',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
'failover' => [],
        'port'     => 3306,
'strictOn' => false,
    ];


    /**
     * This database connection will be used when
     * running the PHPUnit database tests.
     *
     * @var array
     */
    public $tests = [
        'hostname' => '127.0.0.1',
        'username' => '',
        'password' => '',
'DSN'      => '',
        'database' => ':memory:',
        'DBDriver' => 'SQLite3',
'pConnect' => false,
        'DBPrefix' => 'db_',  // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];


    //--------------------------------------------------------------------


    public function __construct()
    {
        parent::__construct();


        // Ensure that we set the database group as 'tests' in case
        // we are running an automated test suite so that
        // we don't overwrite live data accidentally.
        if (ENVIRONMENT === 'testing')
        {
            $this->defaultGroup = 'tests';


            // Under Travis-CI, we can set an ENV var named 'DB_GROUP'
            // so that we can test against multiple databases.
            if ($group = getenv('DB'))
            {
                if (is_file(TESTPATH . 'travis/Database.php'))
                {
                    require TESTPATH . 'travis/Database.php';


                    if (! empty($dbconfig) && array_key_exists($group, $dbconfig))
                    {
                        $this->tests = $dbconfig[$group];
                    }
                }
            }
        }
    }


    //--------------------------------------------------------------------


}

Working with the Controller Class

Next, we will create a controller. We will use the controller to handle all the CRUD operations in the Application. We will create a file in the "CodeIgniter-crud-basic\app\Controllers" folder. We will name it "CrudController.php ."Now, enter the following code:

<?php 
namespace App\Controllers;
use App\Models\CrudModel;
use CodeIgniter\Controller;


class CrudController extends Controller
{
    // show names list in crud codeigniter project
    public function index(){
        $CrudModel = new CrudModel();
        $data['users'] = $CrudModel->orderBy('id', 'DESC')->findAll();
        return view('listname', $data);
    }


    // add name form crud codeigniter project
    public function create(){
        return view('insertname');
    }
 
    // add data crud codeigniter project
    public function store() {
        $CrudModel = new CrudModel();
        $data = [
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
        ];
        $CrudModel->insert($data);
        return $this->response->redirect(site_url('/listname'));
    }


    // show single name crud codeigniter project
    public function singleUser($id = null){
        $CrudModel = new CrudModel();
        $data['user_obj'] = $CrudModel->where('id', $id)->first();
        return view('editname', $data);
    }


    // update name data crud codeigniter project
    public function update(){
        $CrudModel = new CrudModel();
        $id = $this->request->getVar('id');
        $data = [
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
        ];
        $CrudModel->update($id, $data);
        return $this->response->redirect(site_url('/listname'));
    }
 
    // delete name crud codeigniter project
    public function delete($id = null){
        $CrudModel = new CrudModel();
        $data['user'] = $CrudModel->where('id', $id)->delete($id);
        return $this->response->redirect(site_url('/listname'));
    }    
}


In the above code, we are creating a controller class named "CrudController ."It has methods that will help us perform CRUD operations. Following is the flow of the CrudController controller:

  1. It shows the list of names.
     
  2. It has a function to insert a name.
     
  3. It has a function to save the data.
     
  4. It has a function to display a single name.
     
  5. It has a function to update the data of the name.
     
  6. At last, it has a function to delete a name.

Working with Model Class

CodeIgniter has a model class in it. The model class has some methods that we can use to handle the operation related to the database. 

Open the "CodeIgniter-crud-basic\app\Models\CrudModel.php". Now, enter the following code:

<?php 
namespace App\Models;
use CodeIgniter\Model;


class CrudModel extends Model
{
    protected $table = 'names';

    protected $primaryKey = 'id';
    
    protected $allowedFields = ['name', 'email'];
}

Creating Routes for the Application

The next step is to create Routes for the application. These routes will help us handle the CRUD operations. But you need to add and change some rules in the "CodeIgniter-crud-basic\app\Config\Routes.php" file.

<?php namespace Config;

// We will create a new instance of the RouteCollection class in the crud codeigniter project.
$routes = Services::routes();


// Then we will load the system's routing file first so that the app and ENVIRONMENT
// can override as per their need in the crud codeigniter project
if (file_exists(SYSTEMPATH . 'Config/Routes.php'))
{
    require SYSTEMPATH . 'Config/Routes.php';
}

/**
 * --------------------------------------------------------------------
 * Setup of the Router in the crud codeigniter project
 * --------------------------------------------------------------------
 */
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);


/**
 * --------------------------------------------------------------------
 * Definitions of the Routes in the crud codeigniter project
 * --------------------------------------------------------------------
 */


// We will get a performance increase by specifying the default
// route since we don't have to scan any directories.
$routes->get('/', 'Home::index');


// We will add these CRUD Routes.
$routes->get('listname', 'CrudController::index');
$routes->get('insertname', 'CrudController::create');
$routes->post('submit-form', 'CrudController::store');
$routes->get('editname/(:num)', 'CrudController::singleUser/$1');
$routes->post('update', 'CrudController::update');
$routes->get('delete/(:num)', 'CrudController::delete/$1');


if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'))
{
    require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}


After the Structure of the Application is complete, let's make our application come alive. 

Creating Views

Finally, we will create views in our Application. We need to show the output of the application. To create the view, open the "CodeIgniter-crud-basic\app\Views" folder. Now, we will create the following files in the folder:

  • insertname.php
     
  • editname.php
     
  • listname.php
     

Finally, we will put in some code to create the views. So open these files one by one and enter the following code.

listname.php

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, width=device-width, shrink-to-fit=no">
  <title>Codeigniter Crud tutorial on Coding Ninjas</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<div class="container mt-4">
<h1>Codeigniter Crud tutorial on Coding Ninjas </h1>


    <div class="d-flex justify-content-end">
        <a href="<?php echo site_url('/insertname') ?>" class="btn btn-primary">Add a Name & email</a>
   </div>
    <?php
     if(isset($_SESSION['msg'])){
        echo $_SESSION['msg'];
      }
     ?>
  <div class="mt-3">
     <table class="table table-bordered" id="users-list">
       <thead>
          <tr>
             <th>User Id</th>
             <th>Name</th>
             <th>Email</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($users): ?>
          <?php foreach($users as $user): ?>
          <tr>
             <td><?php echo $user['id']; ?></td>
             <td><?php echo $user['name']; ?></td>
             <td><?php echo $user['email']; ?></td>
             <td>
              <a href="<?php echo base_url('editname/'.$user['id']);?>" class="btn btn-warning">Edit</a>
              <a href="<?php echo base_url('delete/'.$user['id']);?>" class="btn btn-danger">Delete</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
  </div>
</div>
 
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<link rel="stylesheet" type="css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script>
    $(document).ready( function () {
      $('#users-list').DataTable();
  } );
</script>
</body>
</html>


In the above code, we are fetching some data from the database. We have also used Jquery and Bootstrap to show the data we are fetching.

Now, open the insertname.php file and enter the following code.

insertname.php

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Crud tutorial on Coding Ninjas</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>


    .container {
      max-width: 500px;
    }


    .error {
      display: block;
      padding-top: 5px;
      font-size: 14px;
      color: red;
    }
  </style>
</head>


<body>
  <div class="container mt-5">
    <form method="post" id="insertname" name="insertname" 
    action="<?= site_url('/submit-form') ?>">
      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control">
      </div>


      <div class="form-group">
        <label>Email ID</label>
        <input type="text" name="email" class="form-control">
      </div>


      <div class="form-group">
        <button type="submit" class="btn btn-success">Add Name and Email</button>
      </div>
    </form>
  </div>


  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
  <script>
    if ($("#add_create").length > 0) {
      $("#add_create").validate({
        rules: {
          name: {
            required: true,
          },
          email: {
            required: true,
            maxlength: 60,
            email: true,
          },
        },
        messages: {
          name: {
            required: "Name is mandatory.",
          },
          email: {
            required: "Email is mandatory.",
            email: "It is not a valid email.",
            maxlength: "The email should be equal to 60 characters.",
          },
        },
      })
    }
  </script>
</body>
</html>


In the "insertname.php," we have created a form for the storage of data in the database. Once we have completed the insertname.php file, we can work on the editname.php file. It will help us to edit the names. Open the editname.php file and enter the following code. 

editname.php

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Crud tutorial on Coding Ninjas</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
   <style> .container {
      max-width: 500px;
    }


    .error {
      display: block;
      padding-top: 5px;
      font-size: 14px;
      color: red;
    }
  </style>
</head>


<body>
  <div class="container mt-5">


  <h1>Codeigniter Crud tutorial on Coding Ninjas</h1>


    <form method="post" id="update_user" name="update_user" 
    action="<?= site_url('/update') ?>">
      <input type="hidden" name="id" id="id" value="<?php echo $user_obj['id']; ?>">


      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control" value="<?php echo $user_obj['name']; ?>">
      </div>


      <div class="form-group">
        <label>Email ID</label>
        <input type="email" name="email" class="form-control" value="<?php echo $user_obj['email']; ?>">
      </div>


      <div class="form-group">
        <button type="submit" class="btn btn-warning">Edit Data</button>
      </div>
    </form>
  </div>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
  <script>
    if ($("#update_user").length > 0) {
      $("#update_user").validate({
        rules: {
          name: {
            required: true,
          },
          email: {
            required: true,
            maxlength: 60,
            email: true,
          },
        },
        messages: {
          name: {
            required: "Name is required.",
          },
          email: {
            required: "Email is required.",
            email: "It does not seem to be a valid email.",
            maxlength: "The email should be or equal to 60 chars.",
          },
        },
      })
    }
  </script>
</body>
</html>


Once you have completed all the above steps, type the following command in the terminal.

php spark serve


Now, open your browser and the following URL:

http://localhost:8080/index.php/listname


Hurray!! You will see the following output:

List of the Names:

output

Add a New Name:

output

Edit a Name:

output

Must Read PHP Projects With Source Code

Frequently Asked Questions

Why do we use a PHP framework?

You can use a PHP framework to reduce development time because frameworks can automate many tasks.

Is PHP front end or back end?

PHP is a back-end language, also known as the scripting language. When any user request a PHP page, the server parses the PHP code. In most cases, it results in dynamically created HTML.

Is PHP Hard to Learn? 

No, PHP is one of the more accessible programming languages to learn. This is because PHP has a robust ecosystem of resources available for beginners and a syntax that forgives beginners.

What is better, PHP or Python?

Python is better for long-term projects. PHP is initially simple to use and has a relatively short learning curve. Python uses pretty strict indentation enforcements. This makes it more readable than PHP.

Should I learn PHP or NodeJS?

While PHP may feel faster to code, Node js provides a much better application speed. It has a non-blocking IO model that allows developers to deploy software that performs significantly quicker.

Conclusion

In this article, we have studied PHP's framework, CodeIgniter. We have studied CRUD in CodeIgniter in detail. We have explained it with an example in detail.

We hope that this article has provided you with the help to enhance your knowledge regarding CodeIgniter and if you would like to learn more, check out our articles on pagination-class-in-codeigniter and yii-vs-codeigniter.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass