CodeIgniter 4 Learn Basics of MySQL CRUD Operation

Reading Time: 11 minutes
13,850 Views

Inside this article we will see the concept i.e CodeIgniter 4 Learn Basics of MySQL CRUD Operation. Article contains the classified information about Basic MySQL CRUD Operation in CodeIgniter 4.

CodeIgniter 4 is an open source framework of PHP. You will see about the concept of CodeIgniter 4 Learn Basics of MySQL CRUD Operation.

CRUD stands for Create, Read, Update, and Delete. It is a term used to describe the basic functions of a database-driven application or system. We will see about each operation of CRUD in CodeIgniter 4 in a very clear way.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need a table. That table will be responsible to store data.

Let’s create table with some columns.

CREATE TABLE `tbl_members` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `mobile` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a table.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


Add Routes

Open Routes.php from /app/Config folder. Add these routes into it.

//...

$routes->match(["get", "post"], "add-member", "Member::addMember");
$routes->match(["get", "post"], "edit-member/(:num)", "Member::editMember/$1");
$routes->get("list-members", "Member::listMember");
$routes->get("delete-member/(:num)", "Member::deleteMember/$1");

//...

Let’s create Model.


Create Model

Back to terminal and run this spark command to create a model file.

$ php spark make:model Member --suffix

It will create MemberModel.php file at /app/Models folder. Open file and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_members';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
      'name', 
      'email', 
      'mobile'
    ];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Create Controller

Loading url Helper

Open BaseController.php from /app/Controllers folder.

Search for $helpers, inside this helpers array simply add this url helper.

protected $helpers = ["url"];

This url helper will load base_url() and site_url() functions.

$ php spark make:controller Member

It will creates Member.php file at /app/Controllers folder.

Open Member.php and write this complete code into it.

<?php

namespace App\Controllers;

use App\Models\MemberModel;

class Member extends BaseController
{
    public function addMember()
    {
        if ($this->request->getMethod() == "post") {

            $rules = [
                "name" => "required|min_length[3]|max_length[40]",
                "email" => "required|valid_email",
                "mobile" => "required|min_length[9]|max_length[15]",
            ];

            if (!$this->validate($rules)) {

                return view('add-member', [
                    "validation" => $this->validator,
                ]);
            } else {

                $memberModel = new MemberModel();

                $data = [
                    'name' => $this->request->getVar("name"),
                    'email' => $this->request->getVar("email"),
                    'mobile' => $this->request->getVar("mobile"),
                ];

                $memberModel->save($data);

                $session = session();
                $session->setFlashdata("success", "Member created successfully");
                return redirect()->to(base_url('list-members'));
            }
        }

        return view('add-member');
    }

    public function listMember()
    {
        $memberModel = new MemberModel();

        $members = $memberModel->findAll();

        return view('list-members', [
            "members" => $members,
        ]);
    }

    public function editMember($id = null)
    {
        $memberModel = new MemberModel();

        $member = $memberModel->where("id", $id)->first();

        if ($this->request->getMethod() == "post") {

            $rules = [
                "name" => "required|min_length[3]|max_length[40]",
                "email" => "required|valid_email",
                "mobile" => "required|min_length[9]|max_length[15]",
            ];

            if (!$this->validate($rules)) {

                return view('edit-member', [
                    "validation" => $this->validator,
                    "member" => $member,
                ]);
            } else {

                $data = [
                    'name' => $this->request->getVar("name"),
                    'email' => $this->request->getVar("email"),
                    'mobile' => $this->request->getVar("mobile"),
                ];

                $memberModel->update($id, $data);

                $session = session();
                $session->setFlashdata("success", "Member updated successfully");
                return redirect()->to(base_url('list-members'));
            }
        }

        return view('edit-member', [
            "member" => $member,
        ]);
    }

    public function deleteMember($id = null)
    {
        $memberModel = new MemberModel();
        $member = $memberModel->delete($id);

        $session = session();
        $session->setFlashdata("success", "Member deleted successfully");

        return redirect()->to(base_url('list-members'));
    }
}
  • if ($this->request->getMethod() == “post”) {} Checking request type
  • $rules = []; Variable which contains form validation rules.
  • if (!$this->validate($rules)) {} Validating form inputs with specified form validation rules. It returns false when form not satisfies any rule.
  • “validation” => $this->validator Sending form validation messages to view file.
  • $memberModel = new MemberModel(); Creating model instance.
  • $memberModel->save($data); Saving form data to database table
  • $session = session(); Loading session service to use
  • $session->setFlashdata(“success”, “Member created successfully”); – Storing session temp data into success key.
  • $memberModel->findAll() Reading all data
  • $memberModel->where(“id”, $id)->first(); Reading single row data on the basis of given specific id value.

Create View Layout Files

We need to create view files.

View files for Add Member, Edit Member, List Member. View files will be created inside /app/Views.

Create Parent Template

Create a layout file inside /app/Views with name app.php. This is be parent layout. Open file app.php and write this complete code into it.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CodeIgniter 4 CRUD Tutorial - OnlineWebTutor</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

   <?= $this->renderSection("body") ?>

</body>
</html>
  

We will extend this template file to every view file and dynamically attach page views in it’s body.

List Member view file

View File – /app/Views/list-members.php

<?= $this->extend("app") ?>

<?= $this->section("body") ?>

<div class="container" style="margin-top:20px;">
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                List Member
                <a href="<?= base_url('add-member') ?>" style="margin-top: -7px;" class="btn btn-info pull-right">Add Member</a>
            </div>
            <div class="panel-body">

                <?php
                    if(session()->has("success")){
                        ?>
                            <div class="alert alert-success">
                                <?= session("success") ?>
                            </div>
                        <?php
                    }
                ?>

                <table class="table">
                    <thead>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Mobile</th>
                        <th>Action</th>
                    </thead>
                    <tbody>
                        <?php
                        foreach ($members as $value) {
                        ?>
                            <tr>
                                <td><?php echo $value['id']; ?></td>
                                <td><?php echo $value['name']; ?></td>
                                <td><?php echo $value['email']; ?></td>
                                <td><?php echo $value['mobile']; ?></td>
                                <td>
                                    <a href="<?= base_url('edit-member/' . $value['id']); ?>" class="btn btn-info">Edit</a>
                                    <a href="<?= base_url('delete-member/' . $value['id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure want to delete?')">Delete</a>
                                </td>
                            </tr>
                        <?php
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

Add Member view file

Create file of add-member.php

Code of /app/Views/add-member.php

<?= $this->extend("app") ?>

<?= $this->section("body") ?>

<div class="container" style="margin-top:20px;">
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                Add Member
                <a href="<?= base_url('list-members') ?>" style="margin-top: -7px;" class="btn btn-info pull-right">List Member</a>
            </div>
            <div class="panel-body">
                <?php if (isset($validation)) : ?>
                    <div class="col-12">
                        <div class="alert alert-danger" role="alert">
                            <?= $validation->listErrors() ?>
                        </div>
                    </div>
                <?php endif; ?>
                <hr>
                <form class="" action="<?= base_url('add-member') ?>" method="post">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" name="name" id="name">
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" name="email" id="email">
                    </div>
                    <div class="form-group">
                        <label for="mobile">Mobile No</label>
                        <input type="text" class="form-control" name="mobile" id="mobile">
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

Edit Member view file

Create file of edit-member.php

Edit Member view file. /app/Views/edit-member.php

<?= $this->extend("app") ?>

<?= $this->section("body") ?>

<div class="container" style="margin-top:20px;">
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                Update Member
                <a href="<?= base_url('list-members') ?>" style="margin-top: -7px;" class="btn btn-info pull-right">List Member</a>
            </div>
            <div class="panel-body">
                <?php if (isset($validation)) : ?>
                    <div class="col-12">
                        <div class="alert alert-danger" role="alert">
                            <?= $validation->listErrors() ?>
                        </div>
                    </div>
                <?php endif; ?>
                <hr>
                <form class="" action="<?= base_url('edit-member/' . $member['id']) ?>" method="post">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" name="name" id="name" value="<?= $member['name'] ?>">
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" name="email" id="email" value="<?= $member['email'] ?>">
                    </div>
                    <div class="form-group">
                        <label for="mobile">Mobile No</label>
                        <input type="text" class="form-control" name="mobile" id="mobile" value="<?= $member['mobile'] ?>">
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

Finally, we have done each configuration of this CodeIgniter 4 CRUD operation.


Application Testing

Open project terminal and start development server via command:

php spark serve

List Member Page – http://localhost:8080/list-members

Add Member Page – http://localhost:8080/add-member

Edit Member Page – http://localhost:8080/edit-member/1

Delete Member URL – http://localhost:8080/delete-member/1

We hope this article helped you to learn about CodeIgniter 4 Learn Basics of MySQL CRUD Operation in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.