Codeigniter 4 Tutorials
- Codeigniter 4
- Application Run
- Application Structure
- Configuration files
- Errors
- Controller
- View
- Model
- How to remove index.php from URL
- Route
- CodeIgniter URLs
- Helper
- Session
- Global Functions and Constants
- Logging Information in CI4
- Error Handling
- Signin / SignUp
- Login / Register
- CRUD
- Crud 1
- Form Validation
- Data Table
- Pagination
- File Upload
- Show Data Using Ajax
- Select2 AJAX Autocomplete Search
- Curl Post
- Rest API
- Weblink
Home » Codeigniter 4 »
How to create CRUD in Codeigniter 4?
Table
File name : users.php
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, 'Mahtab', 'mahtab@gmail.com'),
(2, 'Habib', 'habib@gmail.com'),
(3, 'Sana', 'sana@gmail.com'),
(4, 'mahira', 'mahira@gmail.com'),
(5, 'sara', 'sara@gmail.com'),
(6, 'arham', 'arham@gmail.com');
If anyhow you get the Codeigniter – cannot connect to MySQL database error, then change the hostname value based on your local server e.g XAMPP.
File name : index.php
# XAMPP
public $default = [
...
'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
...
]
Create New Model
UserModel.php file in the app/Models/ folder.
File name : index.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
}
Create CRUD Controller
File name : app/Controllers/UserCrud.php
<?php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
class UserCrud extends Controller
{
// show users list
public function index(){
$userModel = new UserModel();
$data['users'] = $userModel->orderBy('id', 'DESC')->findAll();
return view('user_view', $data);
}
// add user form
public function create(){
return view('add_user');
}
// insert data
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'));
}
// show single user
public function singleUser($id = null){
$userModel = new UserModel();
$data['user_obj'] = $userModel->where('id', $id)->first();
return view('edit_user', $data);
}
// update 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'));
}
// delete user
public function delete($id = null){
$userModel = new UserModel();
$data['user'] = $userModel->where('id', $id)->delete($id);
return $this->response->redirect(site_url('/users-list'));
}
}
Create Routes
File name : app/Config/Routes.php
// 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');
Insert Data in Database Table
Create add_user.php file inside the app/Views/ folder.
File name : index.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 Add User With Validation Demo</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>
Show Data List & Delete
Create app/Views/user_view.php file
File name : index.php
<!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 - positronx.io</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>
Edit and Update Data
create app/Views/edit_view.php file
File name : index.php
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter 4 CRUD - Edit User Demo</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 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>
Start the Application
File name : index.php
php spark serve
File name : index.php
http://localhost:8080/index.php/users-list
File name : index.php