Wednesday, 11 November 2020

PHP Project on Visitor Management System using Ajax jQuery Mysql


Don’t you find it difficult to have the record of all the people who have visited your office yesterday? Just forget about yesterday, do you remember the name of the person who was sitting there in your office for 20 minutes for no reason.

The security requirements of large organizations and infrastructure are challenging and growing increasingly. You can’t say with what intention that person was there in your office. Hence, it’s really necessary to install a visitor management system in the working places for security purposes. Wait!!! Don’t say that you don’t know even a bit about the same.

Don’t worry, below we are going to explain the same. Are you ready???

What Is the Visitor Management System?


As the name itself suggests, it's a kind of special technology which tracks the visitors that enter your working place. Let us tell you that these visitors could be anyone like a contractor, interviewee, consultant, client, or maybe the boyfriend of your Personal Assistant. Hence, it can be said that a visitor is the one who is not a full-time employee.

With the help of this system, you will be able to monitor all the people who are entering your building or office.

Visitor Management System allows you to maintain the record of the visitor in order to save time. It has amazing features like one-click digital records, visitor registration, cloud-based, instant notifications, self-check-in, and checks out. And now Register-based entries are not only inefficient, but they’re also vulnerable and there are chances that can be easily stolen or copied.

So for this reason we have made this Visitor Management system in PHP language by using Ajax with jQuery Bootstrap library. By using this web technology, we have build this small PHP project on smart visitor management system. This is completely web based visitor management system, so user can access visitor data from any place and from any devices in which it can access internet.


PHP Project on Visitor Management System using Ajax jQuery Mysql






Web Technology used for build Visitor Management System


Back-end Side


  • PHP
  • Mysql Database

Front-end Side


  • Ajax
  • jQuery
  • Bootstrap 4
  • HTML 5
  • jQuery DataTables Plugin
  • Parsley.js Form Validation Javascript library
  • Bootstrap Datepicker Plugin
  • Font Awesome Icon Library


Database Structure of Visitor Management System


In below SQL script you can find database stucture of Visitor Management System. So you have to just run following script and tables will be make for this Visitor Management System.


--
-- Database: `visitor_managment_system`
--

-- --------------------------------------------------------

--
-- Table structure for table `admin_table`
--

CREATE TABLE `admin_table` (
  `admin_id` int(11) NOT NULL,
  `admin_name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `admin_contact_no` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `admin_email` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `admin_password` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `admin_profile` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `admin_type` enum('Master','User') COLLATE utf8_unicode_ci NOT NULL,
  `admin_created_on` datetime NOT NULL,
  `admin_status` enum('Enable','Disable') COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `admin_table`
--

INSERT INTO `admin_table` (`admin_id`, `admin_name`, `admin_contact_no`, `admin_email`, `admin_password`, `admin_profile`, `admin_type`, `admin_created_on`, `admin_status`) VALUES
(1, 'John Smith', '8569874587', 'johnsmith@gmail.com', '$2y$10$SY7Mc5BZsLlTjvNl70xhIOCyIVF9G7Xc1xqMzPmaSYTCrH.LG545q', 'images/22041.jpg', 'Master', '2020-11-06 14:17:27', 'Enable'),
(2, 'Donna Huber', '8523698520', 'donnahuber@gmail.com', '$2y$10$2H2wHdkV8GJrV30TouhkXuTcP1gQeAY1rp7EGM4fYzOf/mibjzEg.', 'images/22308.jpg', 'User', '2020-11-08 09:08:33', 'Enable'),
(3, 'Colin Newton', '7453952852', 'colinnewton@gmail.com', '$2y$10$O.7mlW5/JC5ji5nF5YHDfuTFphnSbpsNN7FaQoG1BHEIEg4TVbLKW', 'images/31598.jpg', 'User', '2020-11-09 12:44:57', 'Enable'),
(4, 'Carl Meza', '9632585203', 'carlmeza@gmail.com', '$2y$10$gyv/CokUtimUAdXlQt9aRO8UBTnjSz.FqQQEk24vfQjgTppkFSz4q', 'images/1604922343.png', 'User', '2020-11-09 12:45:44', 'Enable'),
(5, 'Tyron Stein', '96369852635', 'tyronstein@gmail.com', '$2y$10$WIHtgnX5EqrKuruE31exGeZv.CLIHm52CggX1/vn.vr1d4tceFtsq', 'images/1604922395.png', 'User', '2020-11-09 12:46:35', 'Enable'),
(6, 'Peter Parker', '8569852632', 'peterparker@gmail.com', '$2y$10$uBTtPvR0YLH9f4FZt5uumeDz3HOmO8W2c.sNy8pvm7zvo8LHQ5zh.', 'images/6614.jpg', 'User', '2020-11-11 14:00:27', 'Enable');

-- --------------------------------------------------------

--
-- Table structure for table `department_table`
--

CREATE TABLE `department_table` (
  `department_id` int(11) NOT NULL,
  `department_name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `department_contact_person` text COLLATE utf8_unicode_ci NOT NULL,
  `department_created_on` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `department_table`
--

INSERT INTO `department_table` (`department_id`, `department_name`, `department_contact_person`, `department_created_on`) VALUES
(3, 'Marketing', 'Leon Batz, Dessie Labadie, Jayda Keebler', '2020-11-07 08:07:09'),
(4, 'HR', 'Peter Parker', '2020-11-07 08:08:47'),
(5, 'Production', 'Aubrey Nelson, Zayan Humphrey, Harris Lowe, Imaan Villa', '2020-11-09 12:41:59'),
(6, 'Accounting', 'Youssef Hook, Yousef Haigh, Marlie Booker', '2020-11-09 12:42:43'),
(7, 'Purchase', 'Harlee Murillo, Helena Lloyd, Kairon Bauer', '2020-11-09 12:43:17');

-- --------------------------------------------------------

--
-- Table structure for table `visitor_table`
--

CREATE TABLE `visitor_table` (
  `visitor_id` int(11) NOT NULL,
  `visitor_name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `visitor_email` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `visitor_mobile_no` int(12) NOT NULL,
  `visitor_address` tinytext COLLATE utf8_unicode_ci NOT NULL,
  `visitor_meet_person_name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `visitor_department` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `visitor_reason_to_meet` tinytext COLLATE utf8_unicode_ci NOT NULL,
  `visitor_enter_time` datetime NOT NULL,
  `visitor_outing_remark` tinytext COLLATE utf8_unicode_ci NOT NULL,
  `visitor_out_time` datetime NOT NULL,
  `visitor_status` enum('In','Out') COLLATE utf8_unicode_ci NOT NULL,
  `visitor_enter_by` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `visitor_table`
--

INSERT INTO `visitor_table` (`visitor_id`, `visitor_name`, `visitor_email`, `visitor_mobile_no`, `visitor_address`, `visitor_meet_person_name`, `visitor_department`, `visitor_reason_to_meet`, `visitor_enter_time`, `visitor_outing_remark`, `visitor_out_time`, `visitor_status`, `visitor_enter_by`) VALUES
(1, 'Jenny Titus', 'jennytitus@mailinator.com', 2147483647, '1693 Isaacs Creek Road, Decatur, Illinois - 62522', 'Peter Parker', 'HR', 'For Job Interview', '2020-11-02 13:27:44', 'Inteview Completed', '2020-11-02 13:34:45', 'Out', 5),
(2, 'Mary Washington', 'marywashington@gmail.com', 2147483647, '1308 Hornor Avenue, Bartlesville, 74003 Oklahoma', 'Yousef Haigh', 'Accounting', 'For get pending due check...', '2020-11-09 13:29:28', 'This person leave office, without get his due amount.', '2020-11-09 13:34:30', 'Out', 4),
(3, 'Francisco Moyer', 'franciscomoyer@gmail.com', 2147483647, '1256 Ross Street, Metropolis, 62960 - Illinois', 'Jayda Keebler', 'Marketing', 'For get the sample of product.', '2020-11-09 13:31:11', 'Take product and leave our facility.', '2020-11-09 13:33:47', 'Out', 2),
(4, 'Jennifer Brown', 'jenniferbrown@gmail.com', 2147483647, '3870 Summit Park Avenue, Southfield, 48075 Michigan', 'Peter Parker', 'HR', 'For Job Interview...', '2020-11-09 13:33:13', 'Interview Completed..', '2020-11-09 13:35:02', 'Out', 3),
(5, 'Benny Cochran', 'bennycochran@gmail.com', 2147483647, '1930 Seneca Drive, Portland, 97225 Oregon', 'Harris Lowe', 'Production', 'Deliver inventory item like nuts & bolts.', '2020-11-09 13:36:43', 'After deliver item he leave this place.', '2020-11-09 14:39:04', 'Out', 4),
(6, 'Kristina Johnston', 'kristinajohnson@gmail.com', 2147483647, '2730 Felosa Drive, Brownwood, 76801, Texas', 'Kairon Bauer', 'Purchase', 'Give sample product catalog.', '2020-11-09 13:38:21', 'He received our product cataclog from Mr. Kairon', '2020-11-09 14:37:11', 'Out', 5),
(7, 'William Sherrill', 'williamsherrill@gmail.com', 2147483647, '2852 Alfred Drive, Bayside 11361, New York', 'Peter Parker', 'HR', 'For Job Inteview.', '2020-11-09 13:39:58', 'Leave office after completing his inteview.', '2020-11-09 14:34:47', 'Out', 2),
(8, 'Chuck Stjohn', 'chuckstjohn@gmail.com', 2147483647, '3855 Fincham Road, San Diego 92103, California', 'Aubrey Nelson', 'Production', 'For Repair Machine', '2020-11-09 14:14:56', 'After repair machine of production department, he leave this place.', '2020-11-09 14:39:29', 'Out', 4),
(9, 'Francesca Holland', 'francesca_holland@gmail.com', 2147483647, '3944 Hillhaven Drive, Mira Loma 91752, California', 'Peter Parker', 'HR', 'For Job Interview.', '2020-11-09 14:16:11', 'He completed job interview and leave our place.', '2020-11-09 14:37:29', 'Out', 5),
(10, 'Florence Linn', 'florencelinn@yahoo.com', 2147483647, '2920 Valley Drive, Philadelphia 19146, Pennsylvania', 'Harlee Murillo', 'Purchase', 'For give product quote price.', '2020-11-09 14:17:46', 'He give quote price to Mr. Harlee.', '2020-11-09 14:35:18', 'Out', 2),
(11, 'Christa Castaneda', 'chirsta_castaneda@gmail.com', 2147483647, '3377 Smith Road, Hampton 30228, Georgia', 'Marlie Booker', 'Accounting', 'For get the last stationary bill amount', '2020-11-09 14:19:40', 'He received bill amount and leave office.', '2020-11-09 14:33:15', 'Out', 3),
(12, 'Lisa Tschida', 'lisatschida@mail.com', 2147483647, '986 Bassel Street, Metairie 70001, Louisiana', 'Peter Parker', 'HR', 'For Receptionist Post job interview.', '2020-11-09 14:21:03', 'Interview completed', '2020-11-09 14:33:31', 'Out', 3),
(13, 'Anthony Justice', 'anthony.justice@ymail.com', 2147483647, '964 Pointe Lane, Hollywood 33023, Florida', 'Dessie Labadie', 'Marketing', 'For Received new product sample.', '2020-11-09 14:22:35', 'Ms. Dessie give product sample to Anthony and after this he leave this place.', '2020-11-09 14:40:09', 'Out', 4),
(14, 'William McClure', 'williammcclure@gmail.com', 2147483647, '1411 Elsie Drive, Sergeant Bluff 51054, South Dakota', 'Peter Parker', 'HR', 'For attend Junior Assistance post interview.', '2020-11-09 14:24:11', 'Completed Job Interview.', '2020-11-09 14:37:51', 'Out', 5),
(15, 'Kevin Greene', 'kevingreene@gmail.com', 2147483647, '2786 Armbrester Drive, Rancho Dominguez 90220, California', 'Jayda Keebler', 'Marketing', 'For repair office AC.', '2020-11-09 14:25:33', 'Kevin complete working on repairing of Marketing department AC.', '2020-11-09 14:35:57', 'Out', 2),
(16, 'Misty Pedersen', 'mistypedersen@gmail.com', 2147483647, '4975 Sardis Station, Minneapolis 55402, Minnesota', 'Harlee Murillo', 'Purchase', 'For deliver courier.', '2020-11-09 14:26:59', 'Send courier to Harlee and leave our place.', '2020-11-09 14:34:02', 'Out', 3),
(17, 'Kevin Fenner', 'kevinfenner@gmail.com', 2147483647, '1329 Ray Court, Rockingham 28379, North Carolina', 'Yousef Haigh', 'Accounting', 'Deliver Lunch Tiffin.', '2020-11-09 14:28:19', 'Kevein deliver tiffin to Youset and leave this place.', '2020-11-09 14:40:35', 'Out', 4),
(18, 'Ray McGee', 'raymcgee@gmail.com', 2147483647, '2620 Vineyard Drive, Garfield Heights\r\n 44128, Ohio', 'Youssef Hook', 'Accounting', 'Give us our electricity bill', '2020-11-09 14:29:48', 'Give electricity bill to Youssef of Accounting department and then after leave our place.', '2020-11-09 14:38:32', 'Out', 5),
(19, 'Antonio Krouse', 'antoniokrouse@gmail.com', 2147483647, '414 Hilltop Haven Drive, Rochelle Park 07662, New Jersey', 'Harris Lowe', 'Production', 'For deliver new electrical motor.', '2020-11-09 14:31:22', 'Mr. Harris has received electrical motor from Antonio and and Mr. Antonio leave our office.', '2020-11-09 14:36:40', 'Out', 2),
(20, 'Florence Graham', 'florencegraham@gmail.com', 2147483647, '4441 Patton Lane, Garner 27529, North Carolina', 'Peter Parker', 'HR', 'For Attend receptionist job interview.', '2020-11-09 14:32:47', 'Interview Completed.', '2020-11-09 14:34:18', 'Out', 3),
(21, 'Eliana Martinez', 'elianamartinez@gmail.com', 2147483647, '1137 Nash Street Northbrook, IL 60062', 'Peter Parker', 'HR', 'For Job Interview', '2020-11-11 06:09:55', 'Interview completed and leave our premises.', '2020-11-11 06:19:44', 'Out', 2),
(22, 'Andru Symonds', 'andrusymonds@gmail.com', 2147483647, '1881 Progress Way Cedar Rapids, IA 52401', 'Youssef Hook', 'Accounting', 'Amazon Delivery boy for deliver item of Youssef Hook', '2020-11-11 10:29:29', 'He gave parcel to Youset Hook and leave our facility.', '2020-11-11 10:29:58', 'Out', 3),
(23, 'Adam Smith', 'adamsmith@gmail.com', 2147483647, '964 Pointe Lane, Hollywood 33023, Florida', 'Peter Parker', 'HR', 'For Job Interview.', '2020-11-11 14:24:58', 'Job Interview Completed.', '2020-11-11 14:26:48', 'Out', 6);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admin_table`
--
ALTER TABLE `admin_table`
  ADD PRIMARY KEY (`admin_id`);

--
-- Indexes for table `department_table`
--
ALTER TABLE `department_table`
  ADD PRIMARY KEY (`department_id`);

--
-- Indexes for table `visitor_table`
--
ALTER TABLE `visitor_table`
  ADD PRIMARY KEY (`visitor_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admin_table`
--
ALTER TABLE `admin_table`
  MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT for table `department_table`
--
ALTER TABLE `department_table`
  MODIFY `department_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;

--
-- AUTO_INCREMENT for table `visitor_table`
--
ALTER TABLE `visitor_table`
  MODIFY `visitor_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;


Feature of Visitor Management System


Admin Side


  1. Admin can manage all sub user visitor data.
  2. Admin can complete Visitor Analytics of this System.
  3. Admin can Create new user, edit existing user details and enable or disable sub user login.
  4. Admin can Add New Department with multiple person, edit existing department data and delete department data also.
  5. Admin can Add edit or delete Visitor data.
  6. Admin filter visitor data in date range filter.
  7. Admin can export visitor data in CSV file.
  8. Admin can change his profile details with profile picture.
  9. Admin can change his password.

Sub User Side


  1. Sub User can login into this Visitor Management System.
  2. Sub User can view his visitor entry data, Sub user can add new visitor data or edit and delete existing visitor data.
  3. Sub User can enter outing remarks of his Visitor entry.
  4. Sub User can filter his visitor data in date range filter.
  5. Sub User can export his visitor data in CSV file.
  6. Sub User can manage his profile details like name, email, contact number or even profile image also.
  7. Sub User can change his password details.

So, this are the key feature of this visitor management system, which has been make by using PHP language with Mysql database, jquery, Ajax and Bootstrap 4 library. We will provide source code of Visitor Management System so you can build your own Visitor management system from scratch and you can learn how to build web application project in PHP from scratch.

If you have any query or inputs regarding this Visitor Management System, you can write in comment box, we will reply on your comment.

Tuesday, 10 November 2020

Dynamically Add Item to jQuery Select2 Control using Ajax with PHP



Do you know How to add option in Select2 jQuery plugin using Ajax with PHP language, If you not know then you have come on the right place because in this post you can find How to dynamically add option in Select2 jQuery plugin in PHP script using ajax. Here dynamically add option means that means you can add new option on page without going to another page and that option will be add in select2 jQuery plugin and that option will also store in Mysql database. So when you have filled form second time and at that time then you can also select last added option in select2 jquery plugin. This all process will be dynamically so when you have add new option then that data will be stored in database, so it is called dynamically added option in select2 jQuery plugin.

What is jQuery Select2 plugin?


jQuery Select2 plugin is a jquery plugin which has been used for convert simple select box to advance level select box, and after using Select2 plugin we can do searching feature in Select box, we can load remove data in select box, and it will also provide infinite scrolling of options result also. This Select2 plugin is also compatible with Bootstrap 3 and Bootstrap 4 library also. So we can easily use Select2 plugin with Bootstrap library also.


Which Web Technology used Under this Tutorial


Back-end Side


  1. PHP Script
  2. Mysql Database

Front-end Side


  1. jQuery
  2. Ajax
  3. Bootstrap 4
  4. Select2 jQuery Plugin





Mysql Database


First we have to create category table in our Mysql database. So for this run following SQL script in your mysql database. So it will make category table in your local database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `category`
--

CREATE TABLE `category` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `category`
--

INSERT INTO `category` (`category_id`, `category_name`) VALUES
(1, 'Automobile'),
(2, 'Chemicals'),
(5, 'Machinery'),
(6, 'Transport'),
(7, 'Computer'),
(8, 'Food'),
(9, 'Electronics');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `category`
--
ALTER TABLE `category`
  ADD PRIMARY KEY (`category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `category`
--
ALTER TABLE `category`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;





In this tutorial we have use above web technology, now we have proceed for how can we dynamically add option to select2 control. So first we have we have to fetch data from category table and then after we have load that data in HTML Select tag. So it it will fill select box with dynamic Mysql data.

Next we want to initialize Select2 plugin, so we have use $('.select2').select2() this method. This method will convert simple select box to advance level selectbox with searching or filtering feature. For add new option, we have to add tags:true option under this select2() method.

After this for add new option, we have use select2:close event. So when we have type something in select box and close that select box then this event occure and at that time we will trigger Ajax request, which will send Ajax request to PHP script for add new option into Mysql category table and on success of Ajax request it will append newly option to Select2 control.

At PHP script, First it will check category already exist in Mysql table or not. If category not exists in table then it will insert new category into Mysql table and that option will be load in select2 select box. So this is complete process of dynamically add option to Select2 jQuery plugin using Ajax with PHP script. Below you can find complete source code of this tutorial.

Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

?>


index.php



<?php

//index.php

include('database_connection.php');

$query = "
  SELECT * FROM category 
ORDER BY category_name ASC
";

$result = $connect->query($query);

?>

<!DOCTYPE html>
<html>
  <head>
    <title>Dynamically Add New Option in Select2 using Ajax in PHP</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    	<!-- CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    
    <link href="https://raw.githack.com/ttskch/select2-bootstrap4-theme/master/dist/select2-bootstrap4.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
  </head>
  <body>
  	<div class="container">
  		<br />
  		<br />
    	<h1 align="center">Dynamically Add New Option Tag in Select2 using Ajax in PHP</h1>
    	<br />
    	<br />	
      <div class="row">
        <div class="col-md-6 offset-md-3">
          <select name="category" id="category" class="form-control form-control-lg select2">
            <?php
            foreach($result as $row)
            {
              echo '<option value="'.$row['category_name'].'">'.$row['category_name'].'</option>';
            }
            ?>
          </select>
        </div>
      </div> 
    </div>
  </body>
</html>

<script>

$(document).ready(function(){

  $('.select2').select2({
    placeholder:'Select Category',
    theme:'bootstrap4',
    tags:true,
  }).on('select2:close', function(){
    var element = $(this);
    var new_category = $.trim(element.val());

    if(new_category != '')
    {
      $.ajax({
        url:"add.php",
        method:"POST",
        data:{category_name:new_category},
        success:function(data)
        {
          if(data == 'yes')
          {
            element.append('<option value="'+new_category+'">'+new_category+'</option>').val(new_category);
          }
        }
      })
    }

  });

});

</script>


add.php



<?php

//add.php

include('database_connection.php');

if(isset($_POST["category_name"]))
{
	$category_name = preg_replace('/[^a-zA-Z0-9_ -]/s', '', $_POST["category_name"]);

	$data = array(
		':category_name'	=>	$category_name
	);

	$query = "
	SELECT * FROM category 
	WHERE category_name = :category_name
	";

	$statement = $connect->prepare($query);

	$statement->execute($data);

	if($statement->rowCount() == 0)
	{
		$query = "
		INSERT INTO category 
		(category_name) 
		VALUES (:category_name)
		";

		$statement = $connect->prepare($query);

		$statement->execute($data);

		echo 'yes';
	}
}

?>


Conclusion


In this post we have seen How to dynamically add option to select2 element using Ajax with jQuery and PHP. This feature mainly works if you fill some form and at the time of selection from select box and you want option which has not available in select box then by using this dynamically adding option feature will use for add new option into Select2 element without going to another page.

Lastly, If you have found that this tutorial is helpful to you then do not forget to share this post.

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.