Codeigniter 4 ToDo List with Bootstrap and MySQL : CRUD Tutorial with Example

In this Codeigniter tutorial, you will learn how to easily create a ToDo list app using CRUD operations. With that, we will use Bootstrap 5 and jQuery DataTable library to make it more user-friendly and eye-pleasing at the same time.

CRUD is a widely used abbreviated term for various Database operations including Create, Read, Update and Delete. In our ToDo application, you will learn how to create new tasks by pushing data into the MySQL database and also listing all the saved tasks into a Datatable powered by the jQuery Database library. In addition to this, each table row task will have an Actions column to Edit or Delete the tasks.

The features of our ToDo app will include:

  • User-friendly interface: The app utilizes Bootstrap 5 to create a modern, responsive, and intuitive design that is easy to navigate.
  • Task creation: Users can create new tasks by entering a title, description, and initial status (Pending or Completed).
  • Task listing: The app displays all tasks in a well-organized table, with the DataTables jQuery plugin providing advanced features such as search, pagination, and sorting.
  • Task editing: Users can easily update the title, description, and status of existing tasks.
  • Task deletion: Users can remove tasks from the list when they are no longer needed.
  • Status display: The app visually represents the status of each task as “Pending” or “Completed” for quick identification.
  • Dynamic data handling: The app performs CRUD operations in real-time, enabling users to manage their tasks efficiently.
  • Database integration: The ToDo app is connected to a MySQL database, ensuring that task information is stored and retrieved securely and reliably.
  • Error handling: The app effectively manages and displays errors, providing a seamless user experience.
  • Scalability: The app’s modular structure allows for easy expansion and customization of features as needed.
Codeigniter 4 ToDo List with Bootstrap and MySQL: CRUD Tutorial
Codeigniter 4 ToDo List with Bootstrap and MySQL: CRUD Tutorial

 

We will be using Bootstrap 5, the latest version of one of the popular UI frameworks to style our application. With this, the Datatable will be created using the jQuery Datable library, which adds a ton of features, including filter search, Pagination, Sorting etc.

In this comprehensive tutorial, you will learn each and every detail from setting up composer and creating a new Codeigniter project to running it successfully on your server.

We will be doing this much stuff in our tutorial going forward:

  • How to set up a CodeIgniter 4 project using Composer.
  • Configuring and connecting the CodeIgniter project to a MySQL database.
  • Creating a MySQL table for a ToDo list application.
  • Building a Model for handling database queries and operations.
  • Creating a Controller for managing the application’s logic and processing user input.
  • Designing Views for displaying and interacting with the data.
  • Implementing Bootstrap 5 for a responsive and modern user interface.
  • Integrating the DataTables jQuery plugin for an enhanced table presentation and functionality.
  • Implementing CRUD (Create, Read, Update, and Delete) operations for managing tasks in the ToDo list application.
  • Handling and displaying errors in CodeIgniter 4.
  • Writing clean and maintainable code with inline comments for better understanding.

 

How to Create CRUD ToDo App in Codeigniter 4?

Here’s the step-by-step tutorial to create a ToDo app in Codeigniter using Bootstrap and jQuery table performing CRUD operations:

Step 1 – Install CodeIgniter 4

Step 2 – Set up the MySQL database

Step 3 – Create the tasks table

Step 4 – Create the TaskModel

Step 5 – Develop the TaskController

Step 6 – Implement the Routes

Step 7 – Design the Views

Step 8 – Handle Errors

Step 9 – Test the ToDo App

 

Prerequisites

Before we begin, ensure that you have the following software installed on your computer:

PHP 7.3 or higher & MySQL: You can simply install the Xampp on your system to install PHP and PHPMyAdmin Database management tool.

Composer: It is a popular dependency management tool for PHP. You can download the latest version of Composer by heading to this link.

 

 

Step 1 – Install CodeIgniter 4

First, we need to install Codeigniter 4 using Composer. Open your terminal and run the following command:

composer create-project codeigniter4/appstarter crud_app

 

The above command will download the Codeigniter project and will name it crud_app for you. Now enter into the application directory:

cd crud_app

Your requirements could not be resolved to an installable set of packages. Problem 1 – codeigniter4/framework[4.0.0, …, v4.3.4] require ext-intl * -> it is missing from your system….

You may face the above issue while creating the new project. Just check this link for a quick resolution.

 

Step 2 – Set up the MySQL database

Next, let’s configure the database connection. Open the app/Config/Database.php file and update the default the group with your MySQL database credentials:

    public array $default = [
        'DSN' => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'todo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
       // ...remaining configurations

If using Xampp, you can easily find out these details by checking this file ‘~C:\xampp\phpMyAdmin\config.inc.php

If your credential is correct and you see this issue saying “mysqli_sql_exception #1146 Table ‘todo.tasks’ doesn’t exist search

It is mainly caused due the table not yet created in the Database. Make sure you have the defined table in your Database.

 

Step 3 – Create the tasks table

Design the schema for the tasks table, which will include columns such as ID, title, description, and status. After designing the schema, you will create the table in your MySQL database.

You can directly execute the following SQL script to easily create a tasks table in DB named todo.

CREATE TABLE todo (
  id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  description TEXT,
  status TINYINT(1) NOT NULL DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

 

This command creates a table with the following columns:

  • id: Unique identifier for each task (auto-incremented).
  • title: The task’s title (up to 255 characters).
  • description: The task’s description (text).
  • status: The task’s status (0 for pending, 1 for completed).
  • created_at: The timestamp when the task was created (automatically set to the current timestamp).
  • updated_at: The timestamp when the task was last updated (automatically updated to the current timestamp whenever the row is updated).

 

Step 4 – Create the TaskModel

Implement the TaskModel class, which will interact with the tasks table in the database. The TaskModel will include functions for retrieving, inserting, updating, and deleting tasks.

You can create a ~crud_app\app\Models\TaskModel.php file, which will have the following content:

<?php

namespace App\Models;

use CodeIgniter\Model;

class TaskModel extends Model
{
    protected $table = 'tasks';
    protected $primaryKey = 'id';
    protected $allowedFields = ['title', 'description', 'status'];

    public function getTasks()
    {
        return $this->findAll();
    }

    public function getTaskById($id)
    {
        return $this->where('id', $id)->first();
    }
}

 

Step 5 – Develop the TaskController

Next, create the TaskController class file named TaskController.php at this location ~\app\Controllers , which will handle incoming HTTP requests and perform CRUD operations using the TaskModel.

The controller will include methods for displaying the list of tasks, showing a form to create a new task, saving a new task, editing an existing task, and deleting a task.

<?php

namespace App\Controllers;

use App\Models\TaskModel;
use CodeIgniter\Controller;

class TaskController extends Controller
{
    public function index()
    {
        $taskModel = new TaskModel();
        $data['tasks'] = $taskModel->getTasks();
        return view('tasks/index', $data);
    }

    public function create()
    {
        return view('tasks/create');
    }

    public function store()
    {
        $taskModel = new TaskModel();
        $data = [
            'title' => $this->request->getPost('title'),
            'description' => $this->request->getPost('description'),
            'status' => $this->request->getPost('status')
        ];
        $taskModel->insert($data);
        return redirect()->to('/tasks');
    }

    public function edit($id)
    {
        $taskModel = new TaskModel();
        $data['task'] = $taskModel->getTaskById($id);
        return view('tasks/edit', $data);
    }

    public function update($id)
    {
        $taskModel = new TaskModel();
        $data = [
            'title' => $this->request->getPost('title'),
            'description' => $this->request->getPost('description'),
            'status' => $this->request->getPost('status')
        ];
        $taskModel->update($id, $data);
        return redirect()->to('/tasks');
    }

    public function delete($id)
    {
        $taskModel = new TaskModel();
        $taskModel->delete($id);
        return redirect()->to('/tasks');
    }

    public function checkDbConnection()
    {
        $db = \Config\Database::connect();

        if (!$db->connID) {
            $error = $db->error();
            return "Connection failed: " . print_r($error);
        }

        return "Connected successfully";
    }

}

 

Step 6 – Implement the Routes

Now, we will define the routes in the application for the various actions, such as displaying the list of tasks, showing the form for creating a new task and updating or deleting tasks.

These routes will connect the HTTP requests to the appropriate controller methods. Update this file ~app\Config\Routes.php with the following routes

...

$routes->get('/', 'Home::index');

$routes->get('tasks', 'TaskController::index');
$routes->get('tasks/create', 'TaskController::create');
$routes->post('tasks/store', 'TaskController::store');
$routes->get('tasks/edit/(:num)', 'TaskController::edit/$1');
$routes->post('tasks/update/(:num)', 'TaskController::update/$1');
$routes->get('tasks/delete/(:num)', 'TaskController::delete/$1');
$routes->get('check-db-connection', 'TaskController::checkDbConnection');

...

 

Step 7 – Design the Views

In this step, we will create the necessary view files for the ToDo application under the tasks folder.

This will includes :

index.php for displaying the list of tasks

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ToDo List - Codeigniter 4</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js">
    </script>
    <script type="text/javascript" charset="utf8"
        src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <h2 class="mb-4">ToDo List - MySQL, Bootstrap & DataTables</h2>
        <div class="mb-3">
            <a href="/tasks/create" class="btn btn-primary">Add Task</a>
        </div>
        <table id="tasksTable" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tasks as $task): ?>
                    <tr>
                        <td>
                            <?= $task['title']; ?>
                        </td>
                        <td>
                            <?= $task['description']; ?>
                        </td>
                        <td>
                            <?= $task['status'] == 0 ? 'Pending' : 'Completed'; ?>
                        </td>
                        <td>
                            <a href="/tasks/edit/<?= $task['id']; ?>" class="btn btn-sm btn-warning">Edit</a>
                            <a href="/tasks/delete/<?= $task['id']; ?>" class="btn btn-sm btn-danger"
                                onclick="return confirm('Are you sure you want to delete this task?')">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <script>
        $(document).ready(function () {
            $('#tasksTable').DataTable();
        });
    </script>
</body>

</html>

 

create.php for the form to add a new task

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add Task - Codeigniter 4</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <h2 class="mb-4">Add Task</h2>
        <form action="/tasks/store" method="post">
            <div class="mb-3">
                <label for="title" class="form-label">Title</label>
                <input type="text" class="form-control" id="title" name="title" required>
            </div>
            <div class="mb-3">
                <label for="description" class="form-label">Description</label>
                <textarea class="form-control" id="description" name="description" rows="3" required></textarea>
            </div>
            <div class="mb-3">
                <label for="status" class="form-label">Status</label>
                <select class="form-select" id="status" name="status" required>
                    <option value="pending">Pending</option>
                    <option value="completed">Completed</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Add Task</button>
            <a href="/tasks" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</body>

</html>

 

edit.php for the form to edit an existing task.

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Edit Task - Codeigniter 4</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <h2 class="mb-4">Edit Task</h2>
        <form action="/tasks/update/<?= $task['id']; ?>" method="post">
            <div class="mb-3">
                <label for="title" class="form-label">Title</label>
                <input type="text" class="form-control" id="title" name="title" value="<?= $task['title']; ?>" required>
            </div>
            <div class="mb-3">
                <label for="description" class="form-label">Description</label>
                <textarea class="form-control" id="description" name="description" rows="3"
                    required><?= $task['description']; ?></textarea>
            </div>
            <div class="mb-3">
                <label for="status" class="form-label">Status</label>
                <select class="form-select" id="status" name="status" required>
                    <option value="pending" <?= $task['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="completed" <?= $task['status'] === 'completed' ? 'selected' : ''; ?>>Completed
                    </option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Update Task</button>
            <a href="/tasks" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</body>

</html>

These views will be designed using Bootstrap 5 for a responsive layout and the DataTables jQuery plugin for an interactive user interface.

 

Step 8 – Handle Errors.

To enable error messages in Codeigniter, open the app/Config/Boot/development.php file and set the displayErrorDetails option to true:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

 

Step 9 – Test the ToDo app

Finally, test the application to ensure that all features are working correctly and efficiently. This includes creating, updating, and deleting tasks, as well as verifying that the user interface is responsive and interactive.

php spark serve
Codeigniter 4 ToDo List with Bootstrap and MySQL
Reading All Tasks of ToDo List

 

Codeigniter 4 ToDo List with Bootstrap and MySQL
Showing Edit State when Edit Action is Clicked

 

Codeigniter 4 ToDo List with Bootstrap and MySQL
Adding New Task to the ToDo List

 

Conclusion

In this tutorial, we built a fully functional Codeigniter 4 CRUD application using Bootstrap 4 and MySQL. We demonstrated how to install and configure Codeigniter, integrate Bootstrap and DataTables, create models and controllers, and set up routes and views for CRUD operations. Hope it was helpful..

Leave a Comment

Your email address will not be published. Required fields are marked *