Codeigniter 4 CRUD Generator: Bootstrap and MySQL example

Let’s take a look at this CodeIgniter 4 CRUD generator tutorial with bootstrap and MySQL example. Typically, once you’ve decided on your design, you’ll need a generator so that you don’t have to redo anything in the future.

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations. CRUD functionality is present in almost all systems, and we can presume that every coder has dealt with it at some point.

In this CodeIgniter 4 CRUD generator tutorial, we will also show you how to use the Datatables jQuery plug-in to display data and integrate CodeIgniter with Bootstrap 4.

CodeIgniter 4 CRUD Generator Tutorial

Bootstrap is a free and open-source CSS framework for front-end web development that is responsive and mobile-first. It includes design templates for typography, forms, buttons, navigation, and other interface elements that are based on CSS and JavaScript.

DataTables on the other hand is a table-enhancing plug-in for the jQuery JavaScript framework that quickly adds sorting, pagination, and filtering to simple HTML tables.

Step-1 Configuring CodeIgniter 4

The first step in this CodeIgniter 4 CRUD Generator tutorial is to use the composer package to download a clean CodeIgniter 4 application on your system. Use the following code to implement the first step in this CodeIgniter tutorial.

composer create-project codeigniter4/appstarter

After the project has finished downloading, rename the folder to whatever you like. We will rename the folder to codeigniter-crud-example in our case. After that, run the command below to get into the project folder.

cd codeigniter-crud-example

Step-2 Errors In CodeIgniter Must Be Enabled

This is a crucial stage in this CodeIgniter 4 CRUD Generator tutorial. This is because you may get stuck at almost every level, when first starting with CodeIgniter. Furthermore, it is recommended that you can boost the development process momentum by allowing error reporting and displaying it on-screen. This can be achieved by following the steps below.

  • Firstly, open app/Config/Boot/development.php file.
  • Here, set the display_errors to 1 instead of 0.
  • Now, repeat the same process in app/Config/Boot/production.php file.

ini_set('display_errors', '1');

Step-3 Create a New Database

Then you have to set up a database in order to perform CodeIgniter 4 CRUD operations with MySQL database. This step interprets how to give impetus to database-related work in general. We’ll create a new database called demo, create a username called test in MySQL, and connect to it. Furthermore, we will also be executing CodeIgniter database query to streamline the process.

To keep the momentum going, run the SQL query from PhpMyAdmin to create the users table.

CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
name varchar(100) NOT NULL COMMENT 'Name',
email varchar(255) NOT NULL COMMENT 'Email Address',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Oman Doe', '[email protected]'),
(2, 'Vanya Hargreeves', '[email protected]'),
(3, 'Yasar Hargreeves', '[email protected]'),
(4, 'Mosin Hargreeves', '[email protected]'),
(5, 'Amir Hargreeves', '[email protected]'),
(6, 'Aquib Hargreeves', '[email protected]'),
(7, 'Faiz Handler', '[email protected]');

The next step is to define the database information, such as db name, username, and password in the application/config/database.php file. It will create database connection in CodeIgniter 4 and MySQL. To do that, run the below-mentioned code:

public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'test',
'password' => '4Mu99BhzK8dr4vF1',
'database' => 'demo',
'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,
];

Step-4 Create a New Model

The schema, which is an archetype of table values, is defined using the model. As a result, we must create a new UserModel.php file in the app/Models/ folder. To create the User Model, add the following code to the very same file.

<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
}

Impetus access to the database connection is provided by the model class. It concurrently supports database queries in CodeIgniter, so to move data forward in the database.

Step-5 Create CRUD Controller in CodeIgniter with Bootstrap

In this section of the CodeIgniter 4 CRUD Generator tutorial, we will create a new controller and name it UserCrud.php. This controller will contain CRUD methods for performing CRUD operations such as Create, Read, Update, and Delete. To invoke the CodeIgniter 4 CRUD operations with MySQL, we must include the following code in the app/Controllers/UserCrud.php file.

<?php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
class UserCrud extends Controller
{
public function index(){
$userModel = new UserModel();
$data['users'] = $userModel->orderBy('id', 'DESC')->findAll();
return view('user_view', $data);
}
public function create(){
return view('add_user');
}
public function store() {
$userModel = new UserModel();
$data = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
];
$userModel->insert($data);
return $this->response->redirect(site_url('/users-list'));
}
public function singleUser($id = null){
$userModel = new UserModel();
$data['user_obj'] = $userModel->where('id', $id)->first();
return view('edit_user', $data);
}
public function update(){
$userModel = new UserModel();
$id = $this->request->getVar('id');
$data = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
];
$userModel->update($id, $data);
return $this->response->redirect(site_url('/users-list'));
}
public function delete($id = null){
$userModel = new UserModel();
$data['user'] = $userModel->where('id', $id)->delete($id);
return $this->response->redirect(site_url('/users-list'));
}
}

Step-6 CodeIgniter Routes with Parameters

Now we must design routes to handle CRUD operations. To enable routes in the CodeIgniter CRUD application, add the following code to the app/Config/Routes.php file.

// CRUD RESTful Routes
$routes->get('users-list', 'UserCrud::index');
$routes->get('user-form', 'UserCrud::create');
$routes->post('submit-form', 'UserCrud::store');
$routes->get('edit-view/(:num)', 'UserCrud::singleUser/$1');
$routes->post('update', 'UserCrud::update');
$routes->get('delete/(:num)', 'UserCrud::delete/$1');

Step-7 Insert Data in Database using CodeIgniter 4

Now we’ll look at how to use CodeIgniter to insert data into a MySQL database. Create the add user.php file in the app/Views/ folder, and then paste the following code into it.

<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 Add User With Validation Demo - rcvmhs.org</title>
<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="add_create" name="add_create"
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</label>
<input type="text" name="email" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Update 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 ($("#add_create").length > 0) {
$("#add_create").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>

Step-8 Show & Delete Data List

In this phase of CodeIgniter 4 CRUD Generator tutorial, we’ll use DataTables to display data from a MySQL database in a Codeigniter application. At the same time, we’ll look at how to remove a single user from the database. DataTables is a jQuery (Javascript library)-based table advancement plug-in that aims to bring coherence to the data analysis process by allowing users to add, sort, pagination, and filtering capabilities to basic HTML tables with minimal effort.

Create app/Views/user_view.php file and add the following code inside it.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Codeigniter 4 CRUD App Example - rcvmhs.org</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
<div class="d-flex justify-content-end">
<a href="<?php echo site_url('/user-form') ?>" class="btn btn-success mb-2">Add User</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('edit-view/'.$user['id']);?>" class="btn btn-primary btn-sm">Edit</a>
<a href="<?php echo base_url('delete/'.$user['id']);?>" class="btn btn-danger btn-sm">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="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready( function () {
$('#users-list').DataTable();
} );
</script>
</body>
</html>

Step-9 Insert, Update Delete in CodeIgniter

In the next step of this CodeIgniter 4 CRUD Generator tutorial we have to change the user data directly in the database, we must create the app/Views/edit_view.php file and insert the following code inside it.

<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 CRUD - Edit User Demo - rcvmhs.org</title>
<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="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</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-danger btn-block">Save 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 required.",
},
email: {
required: "Email required.",
email: "It does not seem to be a valid email.",
maxlength: "The email should be or equal to 60 chars.",
},
},
})
}
</script>
</body>
</html>

Step-10 Start your Application

Execute the following command to run this application:

php spark serve

Here is the URL that you have to enter in the browser’s address bar to initiate the CRUD application:

http://localhost:8080/index.php/users-list

We’ve finally finished the CodeIgniter 4 CRUD Generator tutorial. From the beginning of this tutorial, we have arranged everything in the correct order and taken into account all the imperatives. If you’re new to CodeIgniter development, this guide will help you advance your profession.

Please note that the above-mentioned codes are not to be executed as they are. Kindly update the code as per your needs and requirements.

We also recommend checking out Codeigniter Tutorial Compress and Resize Uploaded Image (Version 4) tutorial.

Leave a Comment

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