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.

Thursday, 22 October 2020

Datatables with Livewire in Laravel 8


This is Laravel 8 Livewire DataTable tutorial and in this tutorial, you can learn How to install Livewire Datatable package in Laravel 8 framework and then after you can find the solution of how to implement DataTables in Laravel 8 framework using Livewire DataTable package.

In this post we will use Laravel mediconesystems/livewire-datatables package for implement DataTables in Laravel 8 framework and even you can use this Livewire package with existing version of Laravel 6, Laravel 7 also.

As a Laravel developer, we have know Livewire is a full stack framework which have been used with Laravel framework and by using Livewire we can make dynamic interface without leaving the conform of Laravel. The main benefits of Livewire package is that, if you have using Livewire with Laravel framework, then you do not have to worry about creating jQuery or Ajax code. This is because Livewire package will help your to make jQuery Ajax code using PHP and you application form will be submitted without refresh of web page with Laravel validation.



Now we have come to point of How to implement DataTables with Livewire package in Laravel 8 framework. So for this you have to follow following steps.

  • 1. Download Laravel 8 Framework
  • 2. Make Database connection
  • 3. Create Model Class
  • 4. Create Table in Mysql Database
  • 5. Import Dummy Data into Mysql Table
  • 6. Install Livewire Package
  • 7. Install Livewire DataTables Package
  • 8. Make Livewire Components
  • 9. Create Routes
  • 10. Change in Livewire Component Class File
  • 11. Change in Welcome Blade File
  • 12. Run Laravel Server

1. Download Laravel 8 Framework


In first steps, we have to download latest version of Laravel framework. So we have to go command prompt and write following command.


composer create-project --prefer-dist laravel/laravel livewire_datatable


This command will make livewire_datatable directory and under that directory it will download and install Laravel 8 framework.

2. Make Database connection


After downloading Laravel framework, next we want to make database connection. So for this we have to open .env file and under this file we have to define Mysql database configuration. After define database configuration it will make database connection.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


3. Create Model Class


Once you have make database connection, after this we have to make model class for perform database related operation. For this we have to run following command in command prompt.


php artisan make:model Ld -m


This command will make Ld.php class file under app/Models folder and migration file under database/migrations folder. This migration file we will used for make table in Mysql database.

4. Create Table in Mysql Database


After creating migration file, we have to open migration file and under that file we have to define table definition like define table column, which you can seen below.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLdsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('lds', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('gender');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('lds');
    }
}



Once you have define table column in migration file, next we want to import this table definition to mysql database. For this we have go to command and write following command.


php artisan migrate


This command will migrate above table definition to mysql database and under mysql database it will make lds table.



5. Import Dummy Data into Mysql Table


After creating table in Mysql database using composer, next we want to fill table with dummy data. So for this first we have go to command prompt and write following command.


php artisan make:factory Ld


This command will make factory class file under database/factories folder. So we have to open that factory class and under that class we have to define fake data definition which you can seen below.

database/factories/LdFactory.php

<?php

namespace Database\Factories;

use App\Models\Ld;
use Illuminate\Database\Eloquent\Factories\Factory;

class LdFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Ld::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $gender = $this->faker->randomElement(['Male', 'Female']);
        return [
            'name'      =>  $this->faker->name,
            'email'     =>  $this->faker->unique()->safeEmail,
            'gender'    =>  $gender
        ];
    }
}



Next we have go to command prompt and run following command.


php artisan tinker


This command will enable to write shell script in command prompt. So after enable for write shell script, we have to write following command, which will generate 100 fake data in lds table.


Ld::factory()->count(100)->create()

So this way we can generate fake data using factory class file in Laravel framework.

6. Install Livewire Package


Once you have generate fake data in Mysql table, next we want to install Livewire package in Laravel 8 framework. For this we have go to command prompt and run following command.


composer require livewire/livewire


This command will download and install Livewire package in Laravel 8 framework.

7. Install Livewire DataTables Package


After completing process of installing Livewire package in Laravel framework, next for use DataTable with Livewire package in Laravel framework, we have to download and install Mediconesystems Livewire Datatables package. For this we have to go command prompt and run following command.


composer require mediconesystems/livewire-datatables


This command will download and install Livewire DataTables package in Laravel 8 framework. Now we have can implement Livewire DataTable in Laravel framework.

8. Make Livewire Components


After download and install of Livewire DataTable package, next we want to create livewire component, so we have go to command prompt and run following command.


php artisan make:livewire livewire-datatables


This command will create following two files.


app/Http/Livewire/LivewireDatatables.php
resources/views/livewire/livewire-datatables.blade.php


9. Create Routes

In this step, We have to create routes for Laravel application. So, We have open web.php file from the routes directory of Laravel framework, and update the following routes into the web.php file:

routes/web.php

Route::get('livewire-datatables', function () {
    return view('welcome');
});


10. Change in Livewire Component Class File


In this step, we have to update the LivewireDatatables.php component file with the following code, which has been placed on app/Http/Livewire folder:


<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Ld;
use Illuminate\Support\Str;
use Mediconesystems\LivewireDatatables\Column;
use Mediconesystems\LivewireDatatables\NumberColumn;
use Mediconesystems\LivewireDatatables\DateColumn;
use Mediconesystems\LivewireDatatables\Http\Livewire\LivewireDatatable;

class LivewireDatatables extends LivewireDatatable
{
    public $model = Ld::class;

    function columns()
    {
    	return [
    		NumberColumn::name('id')->label('ID')->sortBy('id'),
    		Column::name('name')->label('Name'),
    		Column::name('email')->label('Email Address'),
    		Column::name('gender')->label('Gender'),
    		DateColumn::name('created_at')->label('Creation Date')
    	];
    }
}




11. Change in Welcome Blade File


Under this step, we have to open resources/views/welcome.blade.php file and update following code under this file.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Datatables with Livewire in Laravel 8</title>
    @livewireStyles
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.9.2/tailwind.min.css" integrity="sha512-l7qZAq1JcXdHei6h2z8h8sMe3NbMrmowhOl+QkP3UhifPpCW2MC4M0i26Y8wYpbz1xD9t61MLT9L1N773dzlOA==" crossorigin="anonymous" />
</head>
<body>
<style>
    .rounded-lg, .rounded-b-none 
    {
        width: 1140px;
    }

    .form-input
    {
        width: 450px;
        height: 30px;
    }
</style>
<div class="container mx-auto">
    <br />
    <div class="flex items-center markdown">
        <h1 style="font-size: 2em;"><b>Datatables with Livewire in Laravel 8</b></h1>
    </div>
    <br />
    <div class="flex mb-4">
        <livewire:livewire-datatables searchable="name, email, gender" exportable />
    </div>
        
</div>
    
</body>
@livewireScripts
</html>


12. Run Laravel Server


This is last step and under this step, we have to open command prompt and run following command which will start Laravel development server.


php artisan serve


After run above command then it will start Laravel Development server and provide us base url of our Laravel application. For check above code we have to hit following url in browser.


http://127.0.0.1:8000/livewire-datatables



Friday, 16 October 2020

How to Convert CSV to JSON in PHP


This is simple and short tutorial on How do we convert CSV file data into JSON format in PHP. In this world of web programming, sometimes we have to make feature like fetch data from CSV file and insert that CSV file data into Mysql database then at that time we have need to convert CSV to JSON. The main purpose of this tutorial is to learn how can we easy way to convert CSV data or file to JSON object using PHP script.

Advantages of CSV


  1. CSV files can be opened or edited by text editors like notepad.
  2. In data-warehouse, CSV follows a reasonably flat, simple schema.
  3. Any programing language to parse CSV data is trivial, generating it's extremely easy.
  4. CSV is safe and may clearly differentiate between the numeric values and text. CSV doesn't manipulate data and stores it as-is.
  5. In CSV, you write column headers just one occasion where as in Excel, you've got to possess a start tag and end tag for every column in each row.
  6. Importing CSV files are often much faster, and it also consumes less memory.
  7. It's easy to programmatically manipulate CSV since, after all, they're simple text files.
  8. CSV are often opened with any text editor in Windows like notepad, MS Excel, Microsoft Works 9, etc.

Advantages of JSON


  1. JSON is a portable that means it can be parse and write are available in many programming languages like JavaScript.
  2. By using JSON we can online transfer large data from source to destination in the form of array or objects.
  3. IN JSON we can transfer data in plain text or unformatted data like comma speratted or delimited data.
  4. JSON is better that XML, this is because it has more sufficient space than XML data structure.
  5. JSON has no tag name and it has structure which is nested braces instead of verbose tags.
  6. In exchange of data JSON is faster than XML.


So here we have seen benefits of CSV and JSON data and both are mainly used for data exchange. But if you have work on any web services than JSON data is mostly used for transmit or exchange of data on the web. So if you have data in CSV file and you have to exchange that data then you must convert that data into JSON format and you can easily exchange data online.

In PHP language there many functions are available for parse or read data from CSV file and then convert that data into PHP array and lastly for convert data into JSON then we can use json_encode() function.



Sample Input CSV Data



Company Name,Address,City,State,ZIP/PIN CODE,Country,Website,Industry,First Name,Last Name,Phone Number,Designation,Email
Cougar Investment,3570 Thunder Road,Mountain View,CA,94041,USA,dealtechs.com,Animal care and service worker,Devin,Taylor,650-564-1816,Animal care and service worker,DevinRTaylor@armyspy.com
Robert Hall,1729 Lyndon Street,Slatington,PA,18080,USA,toksalgida.com,Media,Ruby,Gibson,610-767-5251,News anchor,RubyBGibson@armyspy.com



index.php



<?php

$error = '';

if(isset($_POST["upload_file"]))
{
  if($_FILES['file']['name'])
  {
    $file_array = explode(".", $_FILES['file']['name']);

    $file_name = $file_array[0];

    $extension = end($file_array);

    if($extension == 'csv')
    {
      $column_name = array();

      $final_data = array();

      $file_data = file_get_contents($_FILES['file']['tmp_name']);

      $data_array = array_map("str_getcsv", explode("\n", $file_data));

      $labels = array_shift($data_array);

      foreach($labels as $label)
      {
        $column_name[] = $label;
      }

      $count = count($data_array) - 1;

      for($j = 0; $j < $count; $j++)
      {
        $data = array_combine($column_name, $data_array[$j]);

        $final_data[$j] = $data;
      }

      header('Content-disposition: attachment; filename='.$file_name.'.json');

      header('Content-type: application/json');

      echo json_encode($final_data);

      exit;
    }
    else
    {
      $error = 'Only <b>.csv</b> file allowed';
    }
  }
  else
  {
    $error = 'Please Select CSV File';
  }
}

?>

<!DOCTYPE html>
<html>
  	<head>
    	<title>Convert CSV to JSON using PHP</title>
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
    	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  	</head>
  	<body>
  		<div class="container">
  			<br />
  			<br />
    		<h1 align="center">Convert CSV to JSON using PHP</h1>
    		<br />
    		<div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <?php
            if($error != '')
            {
              echo '<div class="alert alert-danger">'.$error.'</div>';
            }
            ?>
            <form method="post" enctype="multipart/form-data">
              <div class="col-md-6" align="right">Select File</div>
              <div class="col-md-6">
                <input type="file" name="file" />
              </div>
              <br /><br /><br />
              <div class="col-md-12" align="center">
                <input type="submit" name="upload_file" class="btn btn-primary" value="Upload" />
              </div>
            </form>
          </div>
        </div>
    	</div>
    	
  	</body>
</html>



Output JSON Data



[
  {
    "Company Name": "Cougar Investment",
    "Address": "3570 Thunder Road",
    "City": "Mountain View",
    "State": "CA",
    "ZIP/PIN CODE": "94041",
    "Country": "USA",
    "Website": "dealtechs.com",
    "Industry": "Animal care and service worker",
    "First Name": "Devin",
    "Last Name": "Taylor",
    "Phone Number": "650-564-1816",
    "Designation": "Animal care and service worker",
    "Email": "DevinRTaylor@armyspy.com"
  },
  {
    "Company Name": "Robert Hall",
    "Address": "1729 Lyndon Street",
    "City": "Slatington",
    "State": "PA",
    "ZIP/PIN CODE": "18080",
    "Country": "USA",
    "Website": "toksalgida.com",
    "Industry": "Media",
    "First Name": "Ruby",
    "Last Name": "Gibson",
    "Phone Number": "610-767-5251",
    "Designation": "News anchor",
    "Email": "RubyBGibson@armyspy.com"
  }
]



Tuesday, 13 October 2020

How to Implement Google reCaptcha in Codeigniter



This post will covered How to add Google re Captcha in Codeigniter application or in another word How to validate Codeigniter Form data by using Google reCaptcha validation. This is simple post on Integration of Google reCaptcha in PHP Codeigniter framework. In this tutorial, we will step by step describe you implementation of Google reCaptcha in Codeingniter application.

Now in your mind one question will arise why need to Add Google reCaptcha in our Form. So by using this Google reCaptcha, we can reduce form spam entry and it will stop storing spam data in our web application.

What is reCaptcha?


reCaptcha is one of the free services which has been provided by Google and it will protect our online web application from the spam data and abuse. It has been used some advanced risk analysis techniques which will be tells that particular user is humans or bots which has fill form data. So, it is mainly used for reduce spamming in our website.

What are benifits of using reCaptcha


There are several benifits of Google reCaptcha which you can find below.

  • It will protect our website registration form from spamming registration.
  • It will prevent from spam comments
  • It will secured our Online Shopping
  • It will protect our Email Account

So there are many other benifits of adding Google reCaptcha in our Codeigniter website. But now below you can find step by step process for integrate Google recaptcha in Codeigniter framework.




1. Get Google reCaptcha Site Key and Secret Key


In first step we want to get the Google recaptcha Site key and Secret key. So first we have to login into our Google account and then after https://www.google.com/recaptcha/admin/create and register your domain name in which website you want to add. So in below you image you can find data like label, reCAPTCHA type and domain name field. After filling this details, you have to click on submit button.



Once you have click on submit button, then you can get Google reCaptcha site key and secret key which you can see in below image. So you have to copy both key and store in safe place. We will use both key in Codeigniter for integrate Google reCaptcha with Codeigniter framework.



2. Define Base Url in Codeigniter


Before starting coding in Codeigniter framework, we have to first define base url of Codeigniter application. For define base url, we have to open application/config/ config.php and under that file you have define base url at $config['base_url'] in this variable.


$config['base_url'] = 'http://localhost/tutorial/codeigniter/';


3. Make Database Connection


For making MySql Database connection in Codeigniter framework, we have to open application/config/database.php file and under this file we have to define Mysql Database configuration.


$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'testing',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);


4. Make Table in Mysql Database


After making Mysql database connection in Codeigniter framework, next we want to create table in Mysql database. So for create table in Mysql database, we have to run following SQL script in phpMyAdmin and it will make sample_data table will create in Mysql database.


--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `age` varchar(30) NOT NULL,
  `gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;



5. Create Controller in Codeigniter


Codeigniter is a MVC model based framework and under this framework Controllers class has been used for handle http request. So for handle Google reCaptcha validation here we have create application/controllers/Captcha.php file and under this class file we have make following method.

__construct() - This magic method will execute code when object of this class has been created and it will load session library and captcha model class under this class. So we can use both class mehtod under this class.

index() - This is root method of this class and it will display views/captcha.php file html content on web page.

validate() - This method has been received form data from client side and under this method firs it has been check g-recaptcha-response variable value has been set or not. If this variable value is set then only it will execute other code. This variable has been generated by Google reCaptcha site key. And then after for check at server side it has use Secret key and send request reCaptcha api for get response regarding user has give proper answer or not. If from reCaptcha api success variable value has been received that means user has pass google recaptcha validation and then after data will be inserted into Mysql database. So here without Google reCaptcha validation data will not be insert into our system.

application/controllers/Captcha.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Captcha extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->model('captcha_model');
	}

	function index()
	{
		$this->load->view('captcha');
	}

	function validate()
	{
		$captcha_response = trim($this->input->post('g-recaptcha-response'));

		if($captcha_response != '')
		{
			$keySecret = '6LefzNYZAAAAABWAiYy2_X2OiBSZkXdT7K-OoaKW';

			$check = array(
				'secret'		=>	$keySecret,
				'response'		=>	$this->input->post('g-recaptcha-response')
			);

			$startProcess = curl_init();

			curl_setopt($startProcess, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");

			curl_setopt($startProcess, CURLOPT_POST, true);

			curl_setopt($startProcess, CURLOPT_POSTFIELDS, http_build_query($check));

			curl_setopt($startProcess, CURLOPT_SSL_VERIFYPEER, false);

			curl_setopt($startProcess, CURLOPT_RETURNTRANSFER, true);

			$receiveData = curl_exec($startProcess);

			$finalResponse = json_decode($receiveData, true);

			if($finalResponse['success'])
			{
				$storeData = array(
					'first_name'	=>	$this->input->post('first_name'),
					'last_name'		=>	$this->input->post('last_name'),
					'age'			=>	$this->input->post('age'),
					'gender'		=>	$this->input->post('gender')
				);

				$this->captcha_model->insert($storeData);

				$this->session->set_flashdata('success_message', 'Data Stored Successfully');

				redirect('captcha');
			}
			else
			{
				$this->session->set_flashdata('message', 'Validation Fail Try Again');
				redirect('captcha');
			}
		}
		else
		{
			$this->session->set_flashdata('message', 'Validation Fail Try Again');

			redirect('captcha');
		}
	}

}

?>


6. Create Models class in Codeigniter


In Codeigniter models class has been used for perform database related operation and models chass has been created in application/models directory. In this tutorial, we have create Captcha_models.php class file and under this file we have make insert() method which has been used for insert data into Mysql table.

application/models/Captcha_models.php

<?php

class Captcha_model extends CI_Model
{
	function insert($data)
	{
		$this->db->insert('sample_data', $data);
	}
}


7. Create Views file in Codeigniter


Views file has been used for display HTML output in brwoser under this Codeigniter framework and here we have create application/views/captcha.php file. Under this file we have make one html form for get data from user table and for create Google reCaptcha under this form we have create one division tag with class=g-recaptcha and at under this tag we have add data-sitekey and under this attirbute value we have to define Google reCaptcha site key. So by define this site key it will generate Google reCaptcha wiget under this form.

application/views/captcha.php

<html>
<head>
    <title>How to Implement Google reCaptcha in Codeigniter</title>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <div class="container box">
        <br />
        <h2 align="center"><b>How to Implement Google reCaptcha in Codeigniter</b></h2>
        <br />
        <div class="panel panel-default">
            <div class="panel-heading">Fill Form Data</div>
            <div class="panel-body">
                <?php
                if($this->session->flashdata('message'))
                {
                ?>
                    <div class="alert alert-danger">
                        <?php
                        echo $this->session->flashdata('message');
                        ?>
                    </div>
                <?php
                }

                if($this->session->flashdata('success_message'))
                {
                ?>
                    <div class="alert alert-success">
                        <?php
                        echo $this->session->flashdata('success_message');
                        ?>
                    </div>
                <?php
                }
                ?>
                <form method="post" action="<?php echo base_url(); ?>captcha/validate">
                    <div class="form-group">
                        <label>First Name</label>
                        <input type="text" name="first_name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Last Name</label>
                        <input type="text" name="last_name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Age</label>
                        <input type="text" name="age" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Gender</label>
                        <input type="text" name="gender" class="form-control" />
                    </div>
                    <div class="form-group">
                        <div class="g-recaptcha" data-sitekey="6LefzNYZAAAAAIeoFhVYj3T5BoCEo1Yja5DvCRxP"></div>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="send" class="btn btn-success" value="Send" />
                    </div>
                </form>
            </div>
        </div>        
    </div>
</body>
</html>


So, this is complete step by step process for integrate Google reCaptcha under this Codeigniter application and reduce spam entry in your website. This is because without pass Google reCaptcha validation, data will not be entered into our database. So it will reduce spam attack in our website. If you have any query then you can ask in comment box we will reply on your comment regarding your query.