Tuesday, 27 October 2020

Basic MySql CRUD Operation in CodeIgniter 4


This is Codeigniter 4 CRUD (Create, Read, Update, Delete) Operation tutorial with Mysql database. In this post, we will make Codeigniter 4 CRUD application with example of Insert, Update, Delete and Select data from Mysql database. So from this post, you can learn How to create CRUD application Codeigniter 4 framework.

Codeigniter 4 framework is completely different than older version of Codeigniter framework. So for learn new framework, first we need to learn How can we perform basic Select, Insert, Update and delete data from Mysql database under this Codeigniter 4 framework. So for learn basic Mysql database crud operation here we will make simple project in Codeigniter 4 framework and in that project we will fetch data from Mysql table and display on web page with pagination links using Codeigniter 4 framework. Then after we will insert or add data into Mysql table with form data validation by using Codeigniter 4 framework. Once we have add or insert data so after this, we will seen how to edit or update mysql table data in Codeigniter 4 framework and lastly, we will seen how to remove or delete data from Mysql database under this Codeigniter 4 application. So this Crud operation we will perform under this Codeigniter 4 CRUD project.

So, If you want to implement CRUD operation in Codeigniter 4 framework, then you have to follow below steps.

  1. Download Codeigniter 4
  2. Enable Codeigniter 4 Errors
  3. Make Database Connection
  4. Create Models Class
  5. Fetch Data from Mysql Database
  6. Insert or Add data in Mysql Database
  7. Update or Edit Mysql table data
  8. Delete or Remove data from Mysql

Download Codeigniter 4


For download Codeigniter 4 framework, first we need to install Composer in our computer. We can also download Codeigniter 4 framework from it's official site but it is better if we have use composer for download Codeigniter 4 framework. But before download we have some prerequisites for download Codeigniter 4 framework.

  • Install Composer
  • PHP 7.2+
  • Enable PHP Intl Extension

If above all requirement is available in your computer then you can download Codeigniter 4 framework. So for download Codeigniter 4 framework, we have open command prompt and move to directory in which we want to download Codeigniter 4 framework and then after run following command.


composer create-project codeigniter4/appstarter crud


This command will make crud folder in define directory and then after in that folder it will download Codeigniter 4 framework. So this way we can download Codeigniter 4 framework.

Enable Codeigniter 4 Errors


Before we have start making CRUD application in Codeigniter 4 framework, first we want to enable Codeigniter 4 errors, this step is required, if we have not enable display of errors on web page then we cannot figure out where is error has been occure. So before proceed for create CRUD application, first we need to enable Codeigniter 4 errors so it will display errors on web page.

So we have to open app/Config/Boot/development.php this file and set display_errors to 1 in place of zero. And then after we have to open app/Config/Boot/production.php file and in that file also we have to set display_errors value 1 in place of 0. So by changing this it will display any PHP error on web page at the time of CRUD application development.



Make Database Connection


In this steps, we will seen How can we make Mysql database connection. But before making database connection. First we want to make table in our Mysql database. So for this run following .SQL script. This script will make user_table with some data in testing database. So you can use this data form CRUD operation.


--
-- Table structure for table `user_table`
--

CREATE TABLE `user_table` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `gender` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `user_table`
--

INSERT INTO `user_table` (`id`, `name`, `email`, `gender`, `created_at`, `updated_at`) VALUES
(1, 'Mrs. Vella Kassulke IV', 'phoeger@example.net', 'Female', '2020-10-21 18:22:23', '2020-10-21 18:22:23'),
(2, 'Dr. Herbert Abernathy MD', 'fluettgen@example.net', 'Male', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(3, 'Glenna Murphy', 'pkuhic@example.org', 'Male', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(4, 'Ines Fadel', 'eveline.mante@example.com', 'Female', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(5, 'Audreanne Wolf V', 'maryse.cartwright@example.net', 'Female', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(6, 'Mrs. Sydni Emard', 'hills.evalyn@example.org', 'Male', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(7, 'Imelda Prosacco', 'colton55@example.net', 'Female', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(8, 'Mr. Alec Hansen', 'casey.wehner@example.com', 'Male', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(9, 'Shanny O\'Connell PhD', 'kirlin.leopoldo@example.org', 'Male', '2020-10-21 18:22:24', '2020-10-21 18:22:24'),
(10, 'Elouise Hand IV', 'phaley@example.org', 'Female', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(11, 'Augustus Denesik', 'rhammes@example.net', 'Female', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(12, 'Emiliano Schaden Sr.', 'selena.jakubowski@example.com', 'Female', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(13, 'Fabiola Bartoletti DDS', 'bonita.donnelly@example.org', 'Female', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(14, 'Jaiden Farrell', 'hermann.ida@example.com', 'Female', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(15, 'Neha Kunde I', 'langosh.colton@example.com', 'Male', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(16, 'Dr. Troy Schamberger', 'gparker@example.org', 'Male', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(17, 'Kadin Wolf', 'cwhite@example.net', 'Male', '2020-10-21 18:22:25', '2020-10-21 18:22:25'),
(18, 'Timothy Schneider', 'jaylin62@example.net', 'Female', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(19, 'Miss Viviane Gleichner', 'efren.lang@example.com', 'Male', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(20, 'Nya Harber', 'tkutch@example.net', 'Female', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(21, 'Emmanuelle Zieme', 'gustave.kemmer@example.com', 'Male', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(22, 'Mrs. Cheyanne Schroeder', 'ahmed.friesen@example.org', 'Female', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(23, 'Raleigh Upton', 'temmerich@example.org', 'Female', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(24, 'Carey Blick', 'haley.elinore@example.org', 'Female', '2020-10-21 18:22:26', '2020-10-21 18:22:26'),
(25, 'Lennie Lind', 'barton.jazmin@example.com', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(26, 'Riley Gibson', 'vhayes@example.com', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(27, 'Mario Toy', 'justen.nienow@example.org', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(28, 'Tatum Tromp', 'wisozk.celia@example.org', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(29, 'Prof. Rosendo O\'Connell II', 'chad69@example.com', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(30, 'Donald Paucek', 'mertz.gerhard@example.org', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(31, 'Prof. Jevon Feil MD', 'oschulist@example.com', 'Female', '2020-10-21 18:22:27', '2020-10-21 18:22:27'),
(32, 'Miss Savanna Hickle', 'willis.kuhn@example.org', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(33, 'Prof. Demetris Crooks PhD', 'bogan.green@example.org', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(34, 'Major Nienow', 'rudy.haag@example.com', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(35, 'Alexander Braun', 'carli.witting@example.org', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(36, 'Colt Dickens', 'brakus.rebekah@example.org', 'Female', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(37, 'Alden Hane III', 'larkin.ena@example.org', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(38, 'Maximus Lesch', 'lucienne93@example.org', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(39, 'Chanel Heller', 'tiffany.bechtelar@example.com', 'Male', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(40, 'Merlin Koch', 'cassidy36@example.net', 'Female', '2020-10-21 18:22:28', '2020-10-21 18:22:28'),
(41, 'Josianne Halvorson', 'gdouglas@example.net', 'Female', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(42, 'Selmer McKenzie', 'collier.erna@example.com', 'Female', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(43, 'Mrs. Vernice Schmeler', 'senger.felipa@example.org', 'Male', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(44, 'Diana Jaskolski', 'ymueller@example.org', 'Male', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(45, 'Dr. Michael Gottlieb', 'leonard.torp@example.org', 'Male', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(46, 'Pauline Lynch', 'dietrich.kennedi@example.net', 'Male', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(47, 'Hershel Eichmann', 'becker.martine@example.net', 'Male', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(48, 'Tyrel Denesik', 'gfisher@example.org', 'Male', '2020-10-21 18:22:29', '2020-10-21 18:22:29'),
(49, 'Manley Murazik', 'hickle.laurie@example.net', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(50, 'Alta Hauck', 'bella73@example.com', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(51, 'Mrs. Kaela Mitchell', 'orn.neoma@example.com', 'Male', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(52, 'Adam Wilderman', 'murazik.wilhelmine@example.com', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(53, 'Micaela Farrell', 'kutch.turner@example.net', 'Male', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(54, 'Dr. Angie Lynch I', 'hwest@example.com', 'Male', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(55, 'Dr. Dixie Kuhn', 'mae.lebsack@example.net', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(56, 'Rudolph Kozey', 'legros.micheal@example.org', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(57, 'Jazmyne Harvey Jr.', 'leo.kuhic@example.com', 'Male', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(58, 'Mollie Luettgen', 'schristiansen@example.net', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(59, 'Magdalena Beer V', 'bartell.kassandra@example.com', 'Male', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(60, 'Perry Harris', 'dariana.labadie@example.net', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(61, 'Unique Schulist', 'maxime.koepp@example.net', 'Female', '2020-10-21 18:22:30', '2020-10-21 18:22:30'),
(62, 'Magnolia Jacobi', 'greg.swaniawski@example.com', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(63, 'Allie Olson V', 'qgrady@example.org', 'Male', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(64, 'Lilyan Boyle', 'wiegand.kamren@example.net', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(65, 'Dr. Lane Lakin', 'hlynch@example.com', 'Male', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(66, 'Larue Tromp', 'tremblay.shyanne@example.net', 'Male', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(67, 'Shana Gleichner', 'floyd18@example.net', 'Male', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(68, 'Laurie Lemke', 'adella06@example.net', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(69, 'D\'angelo Turcotte I', 'tschaden@example.net', 'Male', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(70, 'Miss Bridgette Jacobs', 'erau@example.net', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(71, 'Mr. Warren Windler I', 'hhuels@example.com', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(72, 'Hester Greenfelder', 'cleveland.schneider@example.com', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(73, 'Ethelyn Russel', 'rtremblay@example.net', 'Female', '2020-10-21 18:22:31', '2020-10-21 18:22:31'),
(74, 'Dr. Carole Cruickshank', 'marjolaine.krajcik@example.com', 'Female', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(75, 'Neva Weber DDS', 'lexie.sauer@example.com', 'Female', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(76, 'Braulio Keeling', 'mackenzie23@example.net', 'Male', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(77, 'Roderick Denesik', 'joel.schoen@example.org', 'Male', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(78, 'Heidi Bahringer', 'ezra17@example.org', 'Male', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(79, 'Prof. Eino O\'Hara', 'noelia.rolfson@example.net', 'Female', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(80, 'Kenny Bernhard', 'ricky.padberg@example.com', 'Female', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(81, 'Prof. Vernie Dickinson', 'cassidy.larkin@example.org', 'Female', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(82, 'Janet Kovacek', 'ibergnaum@example.com', 'Male', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(83, 'Prof. Kiana Altenwerth', 'orlo33@example.net', 'Female', '2020-10-21 18:22:32', '2020-10-21 18:22:32'),
(84, 'Tracy Kris', 'tyreek48@example.net', 'Male', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(85, 'Alverta Gleason', 'cathryn.white@example.com', 'Male', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(86, 'Prof. Emerson McLaughlin PhD', 'tromp.mauricio@example.org', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(87, 'Dr. Georgette Corkery V', 'carolina.breitenberg@example.net', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(88, 'Damon Bechtelar DDS', 'elijah01@example.com', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(89, 'Ike Douglas', 'yrunolfsdottir@example.com', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(90, 'Hal Mraz II', 'champlin.haleigh@example.org', 'Male', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(91, 'Lauriane Borer', 'jacobs.vernie@example.net', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(92, 'Prof. Hettie Price DVM', 'zoey.cole@example.net', 'Male', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(93, 'Maci Block', 'brent.moen@example.net', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(94, 'Prof. Doyle Zieme', 'milan06@example.net', 'Female', '2020-10-21 18:22:33', '2020-10-21 18:22:33'),
(95, 'Jerome Reynolds', 'trantow.judge@example.org', 'Female', '2020-10-21 18:22:34', '2020-10-21 18:22:34'),
(96, 'Dr. Casey Bradtke', 'augustus.pagac@example.org', 'Male', '2020-10-21 18:22:34', '2020-10-21 18:22:34'),
(97, 'Lesley Rippin Jr.', 'jimmie29@example.org', 'Female', '2020-10-21 18:22:34', '2020-10-21 18:22:34'),
(98, 'Kira Deckow', 'vhaag@example.org', 'Male', '2020-10-21 18:22:34', '2020-10-21 18:22:34'),
(99, 'Arch Sporer', 'ikilback@example.org', 'Male', '2020-10-21 18:22:34', '2020-10-21 18:22:34'),
(100, 'Brandyn Bogan', 'abernathy.penelope@example.org', 'Male', '2020-10-21 18:22:34', '2020-10-21 18:22:34'),
(101, 'John Smith', 'johnsmith@gmail.com', 'Male', NULL, NULL),
(102, 'Peter Parker', 'peterparker@gmail.com', 'Female', NULL, NULL),
(103, 'Donna Huber', 'donnahuber@mailinator.com', 'Female', NULL, NULL),
(105, 'Jim Perry', 'jim_perry@gmail.com', 'Male', NULL, NULL),
(106, 'Adams Smith', 'adamsmith@gmail.com', 'Male', NULL, NULL);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_table`
--
ALTER TABLE `user_table`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `user_table_email_unique` (`email`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_table`
--
ALTER TABLE `user_table`
  MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=107;


After this, we have open app/Config/Database.php file and under this file we have to define following Mysql database configuration, which will make Mysql database connection in Codeigniter 4 framework.


public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'testing',
		'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,
	];


Create Models Class


Under this steps we will make Models class for perform database related operation. Under this Codeigniter 4 framework models class has been created under app/Models directory and under this directory we have create CrudModel.php which source code you can seen below.

app/Models/CrudModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class CrudModel extends Model
{
	protected $table = 'user_table';

	protected $primaryKey = 'id';

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

}

?>


Under this class, in $table variable we have define name of database table.

In $primaryKey variable, we have define table's primary key.

In $allowedFields variable, we have define fields name, which will used for database operation.

Fetch Data from Mysql Database


Now we have come on the first operation of CRUD and in this part we will discuss how to fetch data from Mysql table and display on web page in HTML table. For this first we have to create one Controllers class file under app/Controllers with name Crud.php. Below you can find the source code of this controller class file for fetch or read data from Mysql table.

app/Controllers/Crud.php

<?php

namespace App\Controllers;

use App\Models\CrudModel;

class Crud extends BaseController
{
	function index()
	{
		//echo 'Hello Codeigniter 4';

		$crudModel = new CrudModel();

		$data['user_data'] = $crudModel->orderBy('id', 'DESC')->paginate(10);

		$data['pagination_link'] = $crudModel->pager;

		return view('crud_view', $data);
	}
}

?>



Under this class file, first we have import CrudModel class for database operation. For fetch data from Mysql table we have make following method.

index() - This is root method of this Crud controller. Under this method we have create object of CrudModel class and by using this object we have fetch data from user_table by using orderBy() and paginate() method. And for create pagination link, here in Codeigniter 4 framework it has been use pager services. And lastly under this method, view() method has been load crud_view.php file on browser and it has display data from $data variable.

app/Views/crud_view.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Codeigniter 4 Crud Application</title>
    <!--  -->
</head>
<body>
    <div class="container">
        
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Crud Application</h2>

        <?php

        $session = \Config\Services::session();

        if($session->getFlashdata('success'))
        {
            echo '
            <div class="alert alert-success">'.$session->getFlashdata("success").'</div>
            ';
        }

        ?>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col">Sample Data</div>
                    <div class="col text-right">
                        
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Gender</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                        <?php

                        if($user_data)
                        {
                            foreach($user_data as $user)
                            {
                                echo '
                                <tr>
                                    <td>'.$user["id"].'</td>
                                    <td>'.$user["name"].'</td>
                                    <td>'.$user["email"].'</td>
                                    <td>'.$user["gender"].'</td>
                                    <td></td>
                                    <td></td>
                                </tr>';
                            }
                        }

                        ?>
                    </table>
                </div>
                <div>
                    <?php

                    if($pagination_link)
                    {
                        $pagination_link->setPath('crud');

                        echo $pagination_link->links();
                    }
                    
                    ?>

                </div>
            </div>
        </div>

    </div>
 
</body>
</html>
<style>
.pagination li a
{
    position: relative;
    display: block;
    padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
}

.pagination li.active a {
    z-index: 1;
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
}
</style>

Above we can see crud_view.php source code. So in this source code we can see how it has fetch data from user_data variable and display on web page in table format. And for pagination links first it has set path pagination links by using $pagination_link->setPath('crud'); this code and for display pagination links it has use echo $pagination_link->links(); this method. For display success message here it has use session flashdata feature of Codeigniter framework.

Insert or Add data in Mysql Database


In previous steps we have seen How to Fetch or Select data from Mysql table in Codeigniter 4 framework. And now in this steps you can find how to insert or add data into Mysql table with Codeigniter 4 framework. For Insert data first you have to seen source of Crud controller.

app/Controllers/Crud.php

<?php

namespace App\Controllers;

use App\Models\CrudModel;

class Crud extends BaseController
{
	function index()
	{
		//echo 'Hello Codeigniter 4';

		$crudModel = new CrudModel();

		$data['user_data'] = $crudModel->orderBy('id', 'DESC')->paginate(10);

		$data['pagination_link'] = $crudModel->pager;

		return view('crud_view', $data);
	}

	function add()
	{
		return view('add_data');
	}

	function add_validation()
	{
		helper(['form', 'url']);

		$error = $this->validate([
			'name'	=>	'required|min_length[3]',
			'email'	=>	'required|valid_email',
			'gender'=>	'required'
		]);

		if(!$error)
		{
			echo view('add_data', [
				'error' 	=> $this->validator
			]);
		}
		else
		{
			$crudModel = new CrudModel();

			$crudModel->save([
				'name'	=>	$this->request->getVar('name'),
				'email'	=>	$this->request->getVar('email'),
				'gender'=>	$this->request->getVar('gender')
			]);

			$session = \Config\Services::session();

			$session->setFlashdata('success', 'User Data Added');

			return $this->response->redirect(site_url('/crud'));
		}
	}
}

?>

So, here for Insert data we have make following method which has handle insert or add data request in Codeigniter 4 framework.

add() - This method has been load form for received data from User.

add_validation() - This method has been receive insert form data request from add() method. Under this method first we have load required helper class using helper() method. After this we want to validate form data, so here we have validate(), under this method we have define validation rules. If form data not passed under this validation rules, then it will add_data.php view file on browser with validation error. But suppose form data has been passed validation rules then form data will be insert into mysql table by using save() method. Under this method for display success message, it has been used Session library setFlashdata() and lastly form will be redirect to index() method of Crud controller by using redirect() method.

Below you can find source of view file which has been used for process insert data into Mysql table.

app/Views/add_data.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Codeigniter 4 Crud Application</title>
    <!--  -->
</head>
<body>
    <div class="container">
        
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Crud Application</h2>

        <?php

        $validation = \Config\Services::validation();

        ?>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col">Sample Data</div>
                    <div class="col text-right">
                        
                    </div>
                </div>
            </div>
            <div class="card-body">
                <form method="post" action="<?php echo base_url("/crud/add_validation")?>">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="name" class="form-control" />
                        <?php
                        if($validation->getError('name'))
                        {
                            echo '<div class="alert alert-danger mt-2">'.$validation->getError('name').'</div>';
                        }
                        ?>
                    </div>

                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" name="email" class="form-control" />
                        <?php
                        if($validation->getError('email'))
                        {
                            echo "
                            <div class='alert alert-danger mt-2'>
                            ".$validation->getError('email')."
                            </div>
                            ";
                        }
                        ?>
                    </div>

                    <div class="form-group">
                        <label>Gender</label>
                        <select name="gender" class="form-control">
                            <option value="">Select Gender</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>

                        <?php

                        if($validation->getError('gender'))
                        {
                            echo '<div class="alert alert-danger mt-2">
                            '.$validation->getError("gender").'
                            </div>';
                        }

                        ?>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">Add</button>
                    </div>
                </form>
            </div>
        </div>

    </div>
 
</body>
</html>


Under this views file we have make html form for received data from user. Under this view file for display form data validation, here we have use Codeigniter 4 validation services. This has been fetch validation error and display on web page by using getError() method. Under this method we have to define input field name, so that field validation error will be display on web page.

And in crud_view.php file, we have to add create link, which will redirect page to add() method of Crud controller. Source of this file, you can find below.

app/Views/crud_view.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Codeigniter 4 Crud Application</title>
    <!--  -->
</head>
<body>
    <div class="container">
        
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Crud Application</h2>

        <?php

        $session = \Config\Services::session();

        if($session->getFlashdata('success'))
        {
            echo '
            <div class="alert alert-success">'.$session->getFlashdata("success").'</div>
            ';
        }

        ?>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col">Sample Data</div>
                    <div class="col text-right">
                        <a href="<?php echo base_url("/crud/add")?>" class="btn btn-success btn-sm">Create</a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Gender</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                        <?php

                        if($user_data)
                        {
                            foreach($user_data as $user)
                            {
                                echo '
                                <tr>
                                    <td>'.$user["id"].'</td>
                                    <td>'.$user["name"].'</td>
                                    <td>'.$user["email"].'</td>
                                    <td>'.$user["gender"].'</td>
                                    <td></td>
                                    <td></td>
                                </tr>';
                            }
                        }

                        ?>
                    </table>
                </div>
                <div>
                    <?php

                    if($pagination_link)
                    {
                        $pagination_link->setPath('crud');

                        echo $pagination_link->links();
                    }
                    
                    ?>

                </div>
            </div>
        </div>

    </div>
 
</body>
</html>
<style>
.pagination li a
{
    position: relative;
    display: block;
    padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
}

.pagination li.active a {
    z-index: 1;
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
}
</style>


Update or Edit Mysql table data


After inserting of data, now we want to update or edit existing mysql table data. So for update data, first we want create edit button in each row of table. So in below source code, you can find, how to add edit button in each row of table under this app/Views/crud_view.php file.

app/Views/crud_view.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Codeigniter 4 Crud Application</title>
    <!--  -->
</head>
<body>
    <div class="container">
        
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Crud Application</h2>

        <?php

        $session = \Config\Services::session();

        if($session->getFlashdata('success'))
        {
            echo '
            <div class="alert alert-success">
            '.$session->getFlashdata('success').'
            </div>
            ';
        }

        ?>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col">Sample Data</div>
                    <div class="col text-right">
                        <a href="<?php echo base_url('crud/add'); ?>" class="btn btn-success btn-sm">Create</a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Gender</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                        <?php
                        if($user_data)
                        {
                            foreach($user_data as $user)
                            {
                                echo '
                                <tr>
                                    <td>'.$user["id"].'</td>
                                    <td>'.$user["name"].'</td>
                                    <td>'.$user["email"].'</td>
                                    <td>'.$user["gender"].'</td>
                                    <td><a href="'.base_url().'/crud/fetch_single_data/'.$user["id"].'" class="btn btn-sm btn-warning">Edit</a></td>
                                    <td></td>
                                </tr>
                                ';
                            }
                        }
                        ?>

                    </table>
                </div>
                <div>
                    <?php

                    if($pagination_link)
                    {
                        $pagination_link->setPath('crud');

                        echo $pagination_link->links();

                    }

                    ?>

                </div>
            </div>
        </div>

    </div>
 
</body>
</html>
<style>
.pagination li a
{
    position: relative;
    display: block;
    padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
}

.pagination li.active a {
    z-index: 1;
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
}
</style>


After this in views folder, we have create one another file edit_data.php. Under this file, we have to make form for display single user data for change that data. In that formk we have also write code for display validation error using Codeigniter 4 validation library.

app/Views/edit_data.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Edit Data - Codeigniter 4 Crud Application</title>
    <!--  -->
</head>
<body>
    <div class="container">
        
        <?php 

        $validation = \Config\Services::validation();


        ?>
        <h2 class="text-center mt-4 mb-4">Edit Data - Codeigniter 4 Crud Application</h2>
        
        <div class="card">
            <div class="card-header">Edit Data</div>
            <div class="card-body">
                <form method="post" action="<?php echo base_url('crud/edit_validation'); ?>">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="name" class="form-control" value="<?php echo $user_data['name']; ?>">

                        <!-- Error -->
                        <?php 
                        if($validation->getError('name'))
                        {
                            echo "
                            <div class='alert alert-danger mt-2'>
                            ".$validation->getError('name')."
                            </div>
                            ";
                        }
                        ?>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" name="email" class="form-control" value="<?php echo $user_data['email']; ?>">

                        <?php 
                        if($validation->getError('email'))
                        {
                            echo "
                            <div class='alert alert-danger mt-2'>
                            ".$validation->getError('email')."
                            </div>
                            ";
                        }
                        ?>
                    </div>

                    <div class="form-group">
                        <label>Gender</label>
                        <select name="gender" class="form-control">
                            <option value="">Select Gender</option>
                            <option value="Male" <?php if($user_data['gender'] == 'Male') echo 'selected'; ?>>Male</option>
                            <option value="Female" <?php if($user_data['gender'] == 'Female') echo 'selected'; ?>>Female</option>
                        </select>

                        <?php 
                        if($validation->getError('gender'))
                        {
                            echo "
                            <div class='alert alert-danger mt-2'>
                            ".$validation->getError('gender')."
                            </div>
                            ";
                        }
                        ?>
                    </div>

                    <div class="form-group">
                        <input type="hidden" name="id" value="<?php echo $user_data["id"]; ?>" />
                        <button type="submit" class="btn btn-primary">Edit</button>
                    </div>
                </form>
            </div>
        </div>

    </div>
 
</body>
</html>


In controller, we have make two method for handle edit or update existing user data. We have make following method for edit or update mysql table data in Crud.php controllers class.

fetch_single_data($id = null) - This method has received request for fetch single user data from Mysql user_table. So under this method it has use where('id', $id) and first() method for fetch single user data and then after it has load that data in edit_data.php views file for any change or modification of data.

edit_validation() - This method has received update data form request, so when we have submit edit form data, then it has received request for update data. Under this method first it has validate form data and then after by using update() method it has update mysql table data. Below you can find source code of Crud.php controller class.

app/Controllers/Crud.php

<?php

namespace App\Controllers;

use App\Models\CrudModel;

class Crud extends BaseController
{
	function index()
	{

		$crudModel = new CrudModel();

        $data['user_data'] = $crudModel->orderBy('id', 'DESC')->paginate(10);

        $data['pagination_link'] = $crudModel->pager;

        return view('crud_view', $data);
	}

	function add()
	{
		return view('add_data');
	}

	function add_validation()
	{
		helper(['form', 'url']);
        
        $error = $this->validate([
            'name' 	=> 'required|min_length[3]',
            'email' => 'required|valid_email',
            'gender'=> 'required'
        ]);

        

        if(!$error)
        {
        	echo view('add_data', [
                'error' => $this->validator
            ]);
        } 
        else 
        {
            $crudModel = new CrudModel();
            
            $crudModel->save([
                'name'   => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'gender'  => $this->request->getVar('gender'),
            ]);          
            
            $session = \Config\Services::session();

            $session->setFlashdata('success', 'User Data Added');

            return $this->response->redirect(site_url('/crud'));
        }

	}

	// show single user
    function fetch_single_data($id = null)
    {
        $crudModel = new CrudModel();

        $data['user_data'] = $crudModel->where('id', $id)->first();

        return view('edit_data', $data);
    }

    function edit_validation()
    {
    	helper(['form', 'url']);
        
        $error = $this->validate([
            'name' 	=> 'required|min_length[3]',
            'email' => 'required|valid_email',
            'gender'=> 'required'
        ]);

        $crudModel = new CrudModel();

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

        if(!$error)
        {
        	$data['user_data'] = $crudModel->where('id', $id)->first();
        	$data['error'] = $this->validator;
        	echo view('edit_data', $data);
        } 
        else 
        {
	        $data = [
	            'name' => $this->request->getVar('name'),
	            'email'  => $this->request->getVar('email'),
	            'gender'  => $this->request->getVar('gender'),
	        ];

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

        	$session = \Config\Services::session();

            $session->setFlashdata('success', 'User Data Updated');

        	return $this->response->redirect(site_url('/crud'));
        }
    }
}

?>


Delete or Remove data from Mysql


In this Codeigniter 4 Crud application, now we want to learn how to delete or remove data from Mysql table. So first need to create one javascript function, this function will redirect url to delete method of Crud.php controller for delete data from Mysql table, then after we need to make delete button in each row of data. For this we have to go app/Views/crud_view.php file and below you can how to make delete button in each of data.

app/Views/crud_view.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <title>Codeigniter 4 Crud Application</title>
    <!--  -->
</head>
<body>
    <div class="container">
        
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Crud Application</h2>

        <?php

        $session = \Config\Services::session();

        if($session->getFlashdata('success'))
        {
            echo '
            <div class="alert alert-success">'.$session->getFlashdata("success").'</div>
            ';
        }

        ?>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col">Sample Data</div>
                    <div class="col text-right">
                        <a href="<?php echo base_url("/crud/add")?>" class="btn btn-success btn-sm">Create</a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Gender</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                        <?php

                        if($user_data)
                        {
                            foreach($user_data as $user)
                            {
                                echo '
                                <tr>
                                    <td>'.$user["id"].'</td>
                                    <td>'.$user["name"].'</td>
                                    <td>'.$user["email"].'</td>
                                    <td>'.$user["gender"].'</td>
                                    <td><a href="'.base_url().'/crud/fetch_single_data/'.$user["id"].'" class="btn btn-sm btn-warning">Edit</a></td>
                                    <td><button type="button" onclick="delete_data('.$user["id"].')" class="btn btn-danger btn-sm">Delete</button></td>
                                </tr>';
                            }
                        }

                        ?>
                    </table>
                </div>
                <div>
                    <?php

                    if($pagination_link)
                    {
                        $pagination_link->setPath('crud');

                        echo $pagination_link->links();
                    }
                    
                    ?>

                </div>
            </div>
        </div>

    </div>
 
</body>
</html>
<style>
.pagination li a
{
    position: relative;
    display: block;
    padding: .5rem .75rem;
    margin-left: -1px;
    line-height: 1.25;
    color: #007bff;
    background-color: #fff;
    border: 1px solid #dee2e6;
}

.pagination li.active a {
    z-index: 1;
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
}
</style>

<script>
function delete_data(id)
{
    if(confirm("Are you sure you want to remove it?"))
    {
        window.location.href="<?php echo base_url(); ?>/crud/delete/"+id;
    }
    return false;
}
</script>


Next we have to Crud.php controller class and in that class we have make delete method. That method has received get request with id of row of data. Based on that id it will remove data from Mysql table under this Codeigniter 4 CRUD application.

app/Controllers/Crud.php

<?php

namespace App\Controllers;

use App\Models\CrudModel;

class Crud extends BaseController
{
	function index()
	{
		//echo 'Hello Codeigniter 4';

		$crudModel = new CrudModel();

        $data['user_data'] = $crudModel->orderBy('id', 'DESC')->paginate(10);

        $data['pagination_link'] = $crudModel->pager;

        return view('crud_view', $data);
	}

	function add()
	{
		return view('add_data');
	}

	function add_validation()
	{
		helper(['form', 'url']);
        
        $error = $this->validate([
            'name' 	=> 'required|min_length[3]',
            'email' => 'required|valid_email',
            'gender'=> 'required'
        ]);

        

        if(!$error)
        {
        	echo view('add_data', [
                'error' => $this->validator
            ]);
        } 
        else 
        {
            $crudModel = new CrudModel();
            
            $crudModel->save([
                'name'   => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'gender'  => $this->request->getVar('gender'),
            ]);          
            
            $session = \Config\Services::session();

            $session->setFlashdata('success', 'User Data Added');

            return $this->response->redirect(site_url('/crud'));
        }

	}

	// show single user
    function fetch_single_data($id = null)
    {
        $crudModel = new CrudModel();

        $data['user_data'] = $crudModel->where('id', $id)->first();

        return view('edit_data', $data);
    }

    function edit_validation()
    {
    	helper(['form', 'url']);
        
        $error = $this->validate([
            'name' 	=> 'required|min_length[3]',
            'email' => 'required|valid_email',
            'gender'=> 'required'
        ]);

        $crudModel = new CrudModel();

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

        if(!$error)
        {
        	$data['user_data'] = $crudModel->where('id', $id)->first();
        	$data['error'] = $this->validator;
        	echo view('edit_data', $data);
        } 
        else 
        {
	        $data = [
	            'name' => $this->request->getVar('name'),
	            'email'  => $this->request->getVar('email'),
	            'gender'  => $this->request->getVar('gender'),
	        ];

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

        	$session = \Config\Services::session();

            $session->setFlashdata('success', 'User Data Updated');

        	return $this->response->redirect(site_url('/crud'));
        }
    }

    function delete($id)
    {
        $crudModel = new CrudModel();

        $crudModel->where('id', $id)->delete($id);

        $session = \Config\Services::session();

        $session->setFlashdata('success', 'User Data Deleted');

        return $this->response->redirect(site_url('/crud'));
    }
}

?>



CodeIgniter 4 Ajax Crud with datatables and Bootstrap Modals


If you want to add some more feature in above Codeigniter 4 CRUD application, then here we have add one more tutorial in Codeigniter 4 with Ajax and by using Ajax with Codeigniter 4 framework here we have also make single page CRUD application. In this Codeigniter 4 CRUD Application using Ajax, we can searching, sorting, paginate of dynamic data also. This is by using jQuery DataTables plugin with Codeigniter 4 framework. So here we have fetch data from Mysql table and load that data in jQuery DataTables plugin in tabular format in Codeigniter 4 framework. After this for insert update delete data in single page Codeigniter 4 CRUD application, here we have use Bootstrap 4 modals class. So by using Modals pop up feature, we can insert or update mysql table data on same page without going to another page. So this way we can build Single page CRUD application Codeigniter 4 framework by using Ajax with jQuery DataTables plugin and Bootstrap modals. Below you can find complete source code of Ajax CRUD application in Codeigniter 4 framework.

app/Models/Ajax_crudModel.php

<?php

//Ajax_crudModel.php

namespace App\Models;

use CodeIgniter\Model;

class Ajax_crudModel extends Model
{
	protected $table = 'user_table';

	protected $primaryKey = 'id';

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

	public function noticeTable()
	{
		$builder = $this->db->table('user_table');

		return $builder;
	}

	public function button()
	{
		$action_button = function($row){
			return '
				<button type="button" name="edit" class="btn btn-warning btn-sm edit" data-id="'.$row['id'].'">Edit</button>
				&nbsp;
				<button type="button" class="btn btn-danger btn-sm delete" data-id="'.$row['id'].'">Delete</button>
				';
		};

		return $action_button;
	}
}


?>



app/Controllers/Ajax_crud.php

<?php

//Ajax_crud.php

namespace App\Controllers;

use App\Models\Ajax_crudModel;

use monken\TablesIgniter;

class Ajax_crud extends BaseController
{
	function index()
	{
		return view('ajax_crud');
	}

	function fetch_all()
	{
		$crudModel = new Ajax_crudModel();

		$data_table = new TablesIgniter();

		$data_table->setTable($crudModel->noticeTable())
				   ->setDefaultOrder("id", "DESC")
				   ->setSearch(["name", "email"])
				   ->setOrder(["id", "name", "email", "gender"])
				   ->setOutput(["id", "name", "email", "gender", $crudModel->button()]);
		return $data_table->getDatatable();
	}

	function action()
	{
		if($this->request->getVar('action'))
		{
			helper(['form', 'url']);
			$name_error = '';
            $email_error = '';
            $gender_error = '';
            $error = 'no';
            $success = 'no';
            $message = '';

            $error = $this->validate([
            	'name'	=>	'required|min_length[3]',
            	'email'	=>	'required|valid_email',
            	'gender'=>	'required'
            ]);

            if(!$error)
            {
            	$error = 'yes';
            	$validation = \Config\Services::validation();
            	if($validation->getError('name'))
            	{
            		$name_error = $validation->getError('name');
            	}

            	if($validation->getError('email'))
            	{
            		$email_error = $validation->getError('email');
            	}

            	if($validation->getError('gender'))
            	{
            		$gender_error = $validation->getError('gender');
            	}
            }
            else
            {
            	$success = 'yes';
            	if($this->request->getVar('action') == 'Add')
            	{
            		$crudModel = new Ajax_crudModel();
            		$crudModel->save([
            			'name'		=>	$this->request->getVar('name'),
            			'email'		=>	$this->request->getVar('email'),
            			'gender'	=>	$this->request->getVar('gender')
            		]);

            		$message = '<div class="alert alert-success">User Data Added</div>';
            	}

                if($this->request->getVar('action') == 'Edit')
                {
                    $crudModel = new Ajax_crudModel();

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

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

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

                    $message = '<div class="alert alert-success">User Data Updated</div>';
                }
            }

            $output = array(
            	'name_error'	=>	$name_error,
            	'email_error'	=>	$email_error,
            	'gender_error'	=>	$gender_error,
            	'error'			=>	$error,
            	'success'		=>	$success,
            	'message'		=>	$message
            );

            echo json_encode($output);
		}
	}

    function fetch_single_data()
    {
        if($this->request->getVar('id'))
        {
            $crudModel = new Ajax_crudModel();

            $user_data = $crudModel->where('id', $this->request->getVar('id'))->first();

            echo json_encode($user_data);
        }
    }

    function delete()
    {
        if($this->request->getVar('id'))
        {
            $id = $this->request->getVar('id');

            $crudModel = new Ajax_crudModel();

            $crudModel->where('id', $id)->delete($id);

            echo '<div class="alert alert-success">User Data Deleted</div>';
        }
    }
}


?>


app/Views/ajax_crud.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport"
     content="width=device-width, initial-scale=1, user-scalable=yes">
  <link rel="stylesheet" href="<?php echo base_url('/css/bootstrap.min.css'); ?>" >

    <script src="<?php echo base_url('/js/jquery.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/popper.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/bootstrap.min.js'); ?>"></script>

    <link rel="stylesheet" type="text/css" href="<?php echo base_url('/css/datatables.min.css'); ?>"/>
 
    <script type="text/javascript" src="<?php echo base_url('/js/datatables.min.js'); ?>"></script>
  <title>Codeigniter 4 Ajax CRUD Application</title>
    
</head>
<body>
  <div class="container">
    <h2 class="text-center mt-4 mb-4">Codeigniter 4 Ajax CRUD Application</h2>
    <span id="message"></span>
    <div class="card">
      <div class="card-header">
        <div class="row">
          <div class="col">Sample Data</div>
          <div class="col text-right">
            <button type="button" name="add_record" id="add_record" class="btn btn-success btn-sm">Add</button>
          </div>
        </div>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-striped table-bordered" id="sample_table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Action</th>
              </tr>
            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
 
</body>
</html>

<div id="userModal" class="modal fade">
  <div class="modal-dialog">
    <form method="post" id="user_form">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Add Data</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" id="name" class="form-control" />
            <span id="name_error" class="text-danger"></span>
          </div>
          <div class="form-group">
            <label>Email</label>
            <input type="text" name="email" id="email" class="form-control" />
            <span id="email_error" class="text-danger"></span>
          </div>
          <div class="form-group">
            <label>Gender</label>
            <select name="gender" id="gender" class="form-control">
              <option value="">Select Gender</option>
              <option value="Male">Male</option>
              <option value="Female">Female</option>
            </select>
            <span id="gender_error" class="text-danger"></span>
          </div>
        </div>
        <div class="modal-footer">
          <input type="hidden" name="hidden_id" id="hidden_id" />
          <input type="hidden" name="action" id="action" value="Add" />
          <input type="submit" name="submit" id="submit_button" class="btn btn-success" value="Add" />
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </form>
  </div>
</div>

<script>

$(document).ready(function(){
  $('#sample_table').DataTable({
    "order":[],
    "serverSide":true,
    "ajax":{
      url:"<?php echo base_url("/ajax_crud/fetch_all"); ?>",
      type:"POST",
    }
  });

  $('#add_record').click(function(){

    $('#user_form')[0].reset();

    $('.modal-title').text('Add Data');

    $('#name_error').text('');

    $('#email_error').text('');

    $('#gender_error').text('');

    $('#action').val('Add');

    $('#submit_button').val('Add');

    $('#userModal').modal('show');

  });

  $('#user_form').on('submit', function(event){

    event.preventDefault();

    $.ajax({

      url:"<?php echo base_url('/ajax_crud/action'); ?>",

      method:"POST",

      data:$(this).serialize(),

      dataType:"JSON",

      beforeSend:function(){

        $('#submit_button').val('wait...');

        $('#submit_button').attr('disabled', 'disabled');

      }, 

      success:function(data)
      {

        $('#submit_button').val('Add');

        $('#submit_button').attr('disabled', false);

        if(data.error == 'yes')
        {

          $('#name_error').text(data.name_error);

          $('#email_error').text(data.email_error);

          $('#gender_error').text(data.gender_error);

        }
        else
        {

          $('#userModal').modal('hide');

          $('#message').html(data.message);

          $('#sample_table').DataTable().ajax.reload();

          setTimeout(function(){

            $('#message').html('');

          }, 5000);

        }

      }

    })

  });

  $(document).on('click', '.edit', function(){

    var id = $(this).data('id');

    $.ajax({

      url:"<?php echo base_url('/ajax_crud/fetch_single_data'); ?>",

      method:"POST",

      data:{id:id},

      dataType:'JSON',

      success:function(data)
      {

        $('#name').val(data.name);

        $('#email').val(data.email);

        $('#gender').val(data.gender);

        $('.modal-header').text('Edit Data');

        $('#name_error').text('');

        $('#email_error').text('');

        $('#gender_error').text('');

        $('#action').val('Edit');

        $('#submit_button').val('Edit');

        $('#userModal').modal('show');

        $('#hidden_id').val(id);

      }

    })

  });

  $(document).on('click', '.delete', function(){

    var id = $(this).data('id');

    if(confirm("Are you sure you want to remove it?"))
    {

      $.ajax({

        url:"<?php echo base_url('/ajax_crud/delete'); ?>",

        method:"POST",

        data:{id:id},

        success:function(data)
        {

          $('#message').html(data);

          $('#sample_table').DataTable().ajax.reload();

          setTimeout(function(){

            $('#message').html('');

          }, 5000);

        }

      })

    }

  });

});

</script>


At the last, Here we have step by step make CRUD application in Codeigniter 4 framework and we have perform CRUD Operation with Mysql Database in Codeigniter 4 and we have seen How to download Codeigniter 4 frameworkd using Composer, then after we have make database connection in Codeigniter 4 framework, next we have seen how can we enable display of errors at the time of Codeigniter 4 framework and then after we have seen how to fetch and display data on web page in Codeigniter 4. Next we have we seen how to insert update and delete data in Codeigniter 4 framework. So this tutorial will help you to start with Codegniter framework for web development.

1 comment:

  1. please create a tutorial on dynamic pdf Reports in Codeigniter4

    ReplyDelete