CodeIgniter 4 Crud Example Tutorial

Codeigniter

Nicesnippets

32811

12-08-2020


CodeIgniter 4 Crud Example Tutorial

In this example ,I will explain CodeIgniter 4 crud application example tutorial. Here, you will learn how to create crud applications in the CodeIgniter 4 framework and perform crud( insert update delete read operation) with MySQL database.

In this CodeIgniter 4 crud application example tutorial, we will use bootstrap 4 for creating users list and create, edit form in CodeIgniter 4.

Here, I will give you full example for simply first crud using codeigniter 4 as bellow.

Step 1: Download Codeigniter Project


In this step, we will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';

To

public $baseURL = 'http://localhost/demo/';

Step 3: Create Database With Table

In this step, we need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

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',

contact_no varchar(50) NOT NULL COMMENT 'Contact No',

created_at varchar(20) NOT NULL COMMENT 'Created date',

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;

INSERT INTO users(id, name, email, mobile_number, created_at) VALUES

(1, 'Team', 'info@test.com', '9000000001', '2019-01-01'),

(2, 'Admin', 'admin@test.com', '9000000002', '2019-01-02'),

(3, 'User', 'user@test.com', '9000000003', '2019-01-03'),

(4, 'Editor', 'editor@test.com', '9000000004', '2019-01-04'),

(5, 'Writer', 'writer@test.com', '9000000005', '2019-01-05'),

(6, 'Contact', 'contact@test.com', '9000000006', '2019-01-06'),

(7, 'Manager', 'manager@test.com', '9000000007', '2019-01-07'),

(8, 'John', 'john@test.com', '9000000055', '2019-01-08'),

(9, 'Merry', 'merry@test.com', '9000000088', '2019-01-09'),

(10, 'Keliv', 'kelvin@test.com', '9000550088', '2019-01-10'),

(11, 'Herry', 'herry@test.com', '9050550088', '2019-01-11'),

(12, 'Mark', 'mark@test.com', '9050550998', '2019-01-12');

Step 4: Setup Database Credentials

In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.

public $default = [

'DSN' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'demo',

'DBDriver' => 'MySQLi',

'DBPrefix' => '',

'pConnect' => false,

'DBDebug' => (ENVIRONMENT !== 'production'),

'cacheOn' => false,

'cacheDir' => '',

'charset' => 'utf8',

'DBCollat' => 'utf8_general_ci',

'swapPre' => '',

'encrypt' => false,

'compress' => false,

'strictOn' => false,

'failover' => [],

'port' => 3306,

];

Step 5: Create Model and Controller

So go to app/Models/ and create here one model. And you need to create one model name UserModel.php and update the following code into your UserModel.php file:

<?php namespace App\Models;

use CodeIgniter\Database\ConnectionInterface;

use CodeIgniter\Model;

class UserModel extends Model

{

protected $table = 'users';

protected $allowedFields = ['name', 'email'];

}

Create Controller

Now Go to app/Controllers and create a controller name Users.php. In this controller, we will create some method/function. We will build some of the methods like :

-> Index() – This is used to display users’ list.

-> create() – This method is used to display create form.

-> store() – This is method is used to insert into the MySQL database.

-> update() – This is used to validate the form data server-side and update it into the MySQL database.

-> edit() – This method is used to display a single user.

-> delete() – This method is used to delete data from MySQL database.

<?php namespace App\Controllers;

use CodeIgniter\Controller;

use App\Models\UserModel;

class Users extends Controller

{

public function index()

{

$model = new UserModel();

$data['users'] = $model->orderBy('id', 'DESC')->findAll();

return view('users', $data);

}

public function create()

{

return view('create-user');

}

public function store()

{

helper(['form', 'url']);

$model = new UserModel();

$data = [

'name' => $this->request->getVar('name'),

'email' => $this->request->getVar('email'),

];

$save = $model->insert($data);

return redirect()->to( base_url('public/index.php/users') );

}

public function edit($id = null)

{

$model = new UserModel();

$data['user'] = $model->where('id', $id)->first();

return view('public/index.php/edit-user', $data);

}

public function update()

{

helper(['form', 'url']);

$model = new UserModel();

$id = $this->request->getVar('id');

$data = [

'name' => $this->request->getVar('name'),

'email' => $this->request->getVar('email'),

];

$save = $model->update($id,$data);

return redirect()->to( base_url('public/index.php/users') );

}

public function delete($id = null)

{

$model = new UserModel();

$data['user'] = $model->where('id', $id)->delete();

return redirect()->to( base_url('public/index.php/users') );

}

}

Step 6: Create Views

Now we need to create some views file.

The views file name following:

-> users.php

-> create-user.php

-> edit-user.php

Create users.php file inside views folder and update the following code into your file:

<!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 users List Example - Tutsmake.com</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

</head>

<body>

<div class="container mt-5">

<a href="<?php echo site_url('public/index.php/users/create') ?>" class="btn btn-success mb-2">Create</a>

<?php

if(isset($_SESSION['msg'])){

echo $_SESSION['msg'];

}

?>

<div class="row mt-3">

<table class="table table-bordered" id="users">

<thead>

<tr>

<th>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('public/index.php/users/edit/'.$user['id']);?>" class="btn btn-success">Edit</a>

<a href="<?php echo base_url('public/index.php/users/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.4.1.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js" type="text/javascript"></script>

<script>

$(document).ready( function () {

$('#users').DataTable();

} );

</script>

</body>

</html>

Create create-user.php file inside views folder and update the following code into your file:

<!DOCTYPE html>

<html>

<head>

<title>Codeigniter 4 User Form With Validation Example</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>

</head>

<body>

<div class="container">

<br>

<?= \Config\Services::validation()->listErrors(); ?>

<span class="d-none alert alert-success mb-3" id="res_message"></span>

<div class="row">

<div class="col-md-9">

<form action="<?php echo base_url('public/index.php/users/store');?>" name="user_create" id="user_create" method="post" accept-charset="utf-8">

<div class="form-group">

<label for="formGroupExampleInput">Name</label>

<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">

</div>

<div class="form-group">

<label for="email">Email Id</label>

<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">

</div>

<div class="form-group">

<button type="submit" id="send_form" class="btn btn-success">Submit</button>

</div>

</form>

</div>

</div>

</div>

<script>

if ($("#user_create").length > 0) {

$("#user_create").validate({

rules: {

name: {

required: true,

},

email: {

required: true,

maxlength: 50,

email: true,

},

},

messages: {

name: {

required: "Please enter name",

},

email: {

required: "Please enter valid email",

email: "Please enter valid email",

maxlength: "The email name should less than or equal to 50 characters",

},

},

})

}

</script>

</body>

</html>

Create edit-user.php file inside views folder and update the following code into your file:

<!DOCTYPE html>

<html>

<head>

<title>Codeigniter 4 Edit User Form With Validation Example</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>

</head>

<body>

<div class="container">

<br>

<?= \Config\Services::validation()->listErrors(); ?>

<span class="d-none alert alert-success mb-3" id="res_message"></span>

<div class="row">

<div class="col-md-9">

<form action="<?php echo base_url('public/index.php/users/update');?>" name="edit-user" id="edit-user" method="post" accept-charset="utf-8">

<input type="hidden" name="id" class="form-control" id="id" value="<?php echo $user['id'] ?>">

<div class="form-group">

<label for="formGroupExampleInput">Name</label>

<input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name" value="<?php echo $user['name'] ?>">

</div>

<div class="form-group">

<label for="email">Email Id</label>

<input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id" value="<?php echo $user['email'] ?>">

</div>

<div class="form-group">

<button type="submit" id="send_form" class="btn btn-success">Submit</button>

</div>

</form>

</div>

</div>

</div>

<script>

if ($("#edit-user").length > 0) {

$("#edit-user").validate({

rules: {

name: {

required: true,

},

email: {

required: true,

maxlength: 50,

email: true,

},

},

messages: {

name: {

required: "Please enter name",

},

email: {

required: "Please enter valid email",

email: "Please enter valid email",

maxlength: "The email name should less than or equal to 50 characters",

},

},

})

}

</script>

</body>

</html>

Step 7: Start Development server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/users

It will help you..