Create Codeigniter 4 CRUD Todo App with MySQL, Bootstrap 5

In this Codeigniter 4 MySQL CRUD tutorial, we will learn how to build a Todo CRUD (Create, Retrieve, Update, Delete) application in Codeigniter. You will also learn how to use Bootstrap 5 in Codeigniter to build a CRUD app interface and store crud data into MySQL database.

Bootstrap is a powerful open-source CSS framework; we will use it to build the crud app. It is highly beneficial in developing responsive, mobile-first user interfaces.

It comes with predefined CSS and JavaScript-based UI components, which contain typography, forms, buttons, navigation, etc.

In this Codeigniter CRUD example, we will create a simple to-do application. We will create a controller and define the functions to handle the crud process in Codeigniter with the database.

How to Build Codeigniter 4 Todo CRUD App with MySQL

  • Step 1: Creating New Application
  • Step 2: Create Table in Database
  • Step 3: Connecting to Database
  • Step 4: Build Model
  • Step 5: Create Controller Functions
  • Step 6: Build CRUD Routes
  • Step 7: Create New Todo
  • Step 8: Retrieve All Todos
  • Step 9: Update Todo
  • Step 10: Test Todo CRUD App

Creating New Application

If Composer is located on your machine, then without wasting time, run the following command.

composer create-project codeigniter4/appstarter

If you use the below link and execute it in the browser, this link will take you to the official site, from where you can download the latest zipped version of the Codeigniter application.

https://www.codeigniter.com/download

Ensure that you have unzipped the package and have changed the project name; make sure to keep the Codeigniter folder in your server directory.

Create Table in Database

The table has to be present in the database to handle the crud app’s data dynamically. Run the SQL query to create a new table with columns.

CREATE TABLE todos (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    title varchar(100) NOT NULL COMMENT 'Title',
    description varchar(255) NOT NULL COMMENT 'Description',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
 
 
INSERT INTO todos(id, title, description) VALUES
  (1, 'Design Update', 'Send an email update to the team: 9am today'),
  (2, 'Mockup Agency', 'Call the design agency to finalize mockups'),
  (3, 'Recruiters Meeting', 'Touch base with recruiters about new role: Tuesday'),
  (4, 'Engineering Renosance', 'Meet with the engineering team.');

Connecting to Database

Codeigniter offers multiple ways to connect the app to the database, you can update the db details in the Database.php.

Add the username, password and database name in the app/Config/Database.php file.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Build Model

In this step, you have to create a model file; after that, head over to app/Models/TodoModel.php and add the provided code.

<?php 

namespace App\Models;
use CodeIgniter\Model;

class TodoModel extends Model
{

    protected $table = 'todos';
    protected $primaryKey = 'id';
    protected $allowedFields = [
      'title', 
      'description'
    ];

}

Create Controller Functions

Next, head over to the app/Controllers directory, create the TodoController.php file, and create various functions; these functions will add, update, delete, and view todo data.

Update app/Controllers/TodoController.php file.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\TodoModel;


class TodoController extends Controller
{

    public function index(){
        $todoModel = new TodoModel();
        $data['todos'] = $todoModel->orderBy('id', 'DESC')->findAll();
        return view('todo_view', $data);
    }

    public function create(){
        return view('add_todo');
    }
 
    public function store() {
        $todoModel = new todoModel();
        $data = [
            'title' => $this->request->getVar('title'),
            'description'  => $this->request->getVar('description'),
        ];
        $todoModel->insert($data);
        return $this->response->redirect(site_url('/todo-list'));
    }

    public function getTodo($id = null){
        $todoModel = new todoModel();
        $data['todo_obj'] = $todoModel->where('id', $id)->first();
        return view('edit_todo', $data);
    }

    public function update(){
        $todoModel = new todoModel();
        $id = $this->request->getVar('id');
        $data = [
            'title' => $this->request->getVar('title'),
            'description'  => $this->request->getVar('description'),
        ];
        $todoModel->update($id, $data);
        return $this->response->redirect(site_url('/todo-list'));
    }
 
    public function delete($id = null){
        $todoModel = new todoModel();
        $data['todo'] = $todoModel->where('id', $id)->delete($id);
        return $this->response->redirect(site_url('/todo-list'));
    }    
}

Build CRUD Routes

In this step, you need to define the routes, define the get, post methods, pass the controller with its respective functions and route name.

Update app/Config/Routes.php file

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->setDefaultController('TodoController');
$routes->get('todo-list', 'TodoController::index');
$routes->get('todo-form', 'TodoController::create');
$routes->post('add-todo', 'TodoController::store');
$routes->get('edit-todo/(:num)', 'TodoController::getTodo/$1');
$routes->post('update-todo', 'TodoController::update');
$routes->get('delete-todo/(:num)', 'TodoController::delete/$1');

Create New Todo

In this step, you have to create add_todo.php inside the app/Views directory. To create the todo, create a form using Bootstrap and use the jQuery validate to implement the client-side validation in the crud form.

Update app/Views/add_todo.php file.

<!DOCTYPE html>
<html>

<head>
  <title>Codeigniter 4 CRUD Operations Example</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .error {
      display: block;
      color: red;
      font-size: 13px;
    }
  </style>
</head>

<body>
  <div class="container mt-3">
    <form method="post" id="add_todo" name="add_todo" 
    action="<?= site_url('/add-todo') ?>">
      
      <div class="mb-3">
        <input type="text" name="title" class="form-control" placeholder="Title">
      </div>

      <div class="mb-3">
        <input type="text" name="description" class="form-control" placeholder="Description">
      </div>

      <div class="d-grid">
        <button type="submit" class="btn btn-dark">Create</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_todo").length > 0) {
      $("#add_todo").validate({
        rules: {
          title: {
            required: true,
          },
          description: {
            required: true,
            maxlength: 120,
          },
        }
      })
    }
  </script>
</body>

</html>

Retrieve All Todos

In this step, we will show you how to create view template to retrieve all the todo items, you will also see how to delete todo item from the database. Hence, create todo_view.php inside the app/Views folder.

Thereafter, go to app/Views/todo_view.php file and update the code.

<!DOCTYPE html>
<html>

<head>
    <title>Codeigniter 4 CRUD Operations Example</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .error {
            display: block;
            color: red;
            font-size: 13px;
        }
    </style>
</head>

<body>
    <div class="container">

        <div class="d-flex justify-content-end">
            <a href="<?php echo site_url('/todo-form') ?>" class="btn btn-danger mb-3">Create Todo</a>
        </div>

        <?php if(isset($_SESSION['msg'])){
            echo $_SESSION['msg'];
        } ?>

        <ul class="list-group">
            <?php if($todos): ?>
            <?php foreach($todos as $todo): ?>
            <li class="list-group-item">
                <h3><?php echo $todo['title']; ?></h3>
                <p><?php echo $todo['description']; ?></p>
                <p>
                    <a href="<?php echo base_url('edit-todo/'.$todo['id']);?>" class="text-decoration-none">Edit</a>
                    <a href="<?php echo base_url('delete-todo/'.$todo['id']);?>" class="text-decoration-none">Delete</a>
                </p>
            </li>
            <?php endforeach; ?>
            <?php endif; ?>
        </ul>

    </div>
</body>

</html>

Update Todo

In this final step, you need to create edit_todo.php into the app/Views folder. To update the todo, create a form, fetch and add the todo data into the todo form.

Make sure to update app/Views/edit_todo.php file.

<!DOCTYPE html>
<html>

<head>
  <title>Codeigniter 4 TODO CRUD App</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .error {
      display: block;
      color: red;
      font-size: 13px;
    }
  </style>
</head>

<body>
  <div class="container">
    <form method="post" name="update_todo" id="update_todo" action="<?= site_url('/update-todo') ?>">
      
      <input type="hidden" name="id" id="id" value="<?php echo $todo_obj['id']; ?>">

      <div class="mb-3">
        <input type="text" name="title" class="form-control" value="<?php echo $todo_obj['title']; ?>">
      </div>

      <div class="mb-3">
        <input type="text" name="description" class="form-control" value="<?php echo $todo_obj['description']; ?>">
      </div>

      <div class="d-grid">
        <button type="submit" class="btn btn-dark">Update</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_todo").length > 0) {
      $("#update_todo").validate({
        rules: {
          title: {
            required: true,
          },
          description: {
            required: true,
            maxlength: 120,
          },
        }
      })
    }
  </script>
</body>

</html>

Run and Test Application

We have completed with the development, Lastly, start the application with the help of the php spark command.

After running the command, copy the provided url paste in the browser and hit enter to watermark the image.

php spark serve
http://localhost:8080/index.php/todo-form

Create Codeigniter 4 CRUD Todo App with MySQL, Bootstrap

Conclusion

In this detailed example, we went through all the essentials steps and learned how to create CRUD operation in the Codeigniter framework and MySQL.