How to delete records from MySQL table with Ajax in CodeIgniter 4

Let us develop a web application to display, update and delete data using CodeIgniter 4 and MySQL. For deleting we will use Ajax in CodeIgnoiter 4. This application will display a list of students with their details, and for each student, one (say admin) can update or delete (using ajax) the student details.

If you want to know how to install and configure CodeIgniter 4, you can read the topic How to Install and Test CodeIgniter 4 in Your Local Computer

I have implemented this using CodeIgniter 3 also and explained that in another topic. You can read How to Display, Update and Delete Data in CodeIgniter 3 with Ajax.

CodeIgniter: Delete data from MySQL DB using AJAXFolders and Files

I have created a folder named 'projects' in D:\ drive and installed CodeIgniter 4 in student folder under projects. So, the root directory is D:/projects/student.

Delete record with out page refresh in codeigniter

You can see, we have Controller - Student.php, Model - ModelStudent.php and two views under views folder. The folder 'assets' is created under public to keep the stylesheets, JavaScripts and image files. Here I have style.css which is kept in public/assets/css folder and a JavaScript file delStudent.js under public/assets/js folder. Just make sure you give correct path for css file in the views.

If you are using XAMPP and want to use Apache Web Server instead of PHP built-in server, then you can install CodeIgniter 4 under xampp/htdocs/<your folder name>. In our case this folder name is student. I will show necessary configuration changes and test the application for both the web servers.

Step 1 - Create a MySQL table for student details

Let us create the table named 'student' in MySQL database. Table structures is given below:

Table: student

This table stores details of all students.

delete data from database using CodeIgniter Ajax

Below are the columns in this table.

  1. student_id - It is the primary key and auto incremented id of the student
  2. first_name - First name of the student
  3. last_name - Last name of the student
  4. school - School name of the student
Create table script for this table is given below; you can use this code to create the table.

student.sql

After you create the table, please verify if table structure is same as above and the rows are inserted in the table. Rows in the table should be as below:

Delete Record from MySQL Table with AJAX using CodeIgniter 4

Step 2 - Create the views to display list of students and to update a student

There will be two views for displaying list of students (student.php) and updating student details (update_student.php). Additionally, there is a custom css file. Let us take a look at them one by one.

View for displaying students (student.php)

How to use delete method in Ajax

Student view lists the details of the student. Controller sends the student data to the view and using a for loop student rows are displayed in a html table. There are two actions against each student, edit student and delete student. Let's see the code:

app/Views/student.php

For each row thert are two links for editing and deleting the student details. For edit, it calls the updateStudent() method of student controller with student_id as the parameter. For delete, it calls a JavaScript function delStudent() with student_id as the parameter to the function.

Function delStudent()

This JavaScript function runs an Ajax to call deleteStudent() method of the controller to delete record using Ajax. It sends student_id to the controller method. When student row is deleted by the controller method it displays the message and reloads the student list. See the code for the function below, it is included in the delStudent.js file.

assets/js/delStudent.js

In 'url' parameter of Ajax, it calls deleteStudent() method of the student controller. On success it displays the message (success or error) and reloads the page. So if student row is deleted, it will not be shown in the list,as the list gets refreshed.

View to Update student (update_student.php)

How do you delete data in CodeIgniter

Update student page displays a form with the existing values displayed in various fields. When Edit link is clicked, controller method gets the details of the students from database using the student_id. Then it loads this view with the student details. Let's see the code for update_student view:

app/Views/update_student.php

There is a custom stylesheet used in the views. It is given below:

assets/css/style.css

I just added few simple styles here, you can always add better styles.

So, these are the views, now let's go to controller section.

Step 3 - Write Controller code (Student.php)

Our controller class will have three methods, an index() method to display the students, updateStudent() method for updating student details and deleteStudent() method for deleting a student.

In the constructor method, form and url helper are loaded. Then an instance of the model is created.

onclick through delete record in ajax codeigniter

Let us now add the methods updateStudent() and deleteStudent() in the controller.

Controller Method updateStudent()

It gets the details of the student from database and loads the update student view. See the code below:

For validating input fields, rules are defined using $rules. Form validations are performed on the input fields. Then there is a $errors array for custom error messages in case validation fails. For detail how to do form validation, you can read the topic How to Do Form Validation With Custom Rule in CodeIgniter 4.

$this->model->updateStudent($update_data,$student_id) method will update the student row in database table and return true or false.

It gets the student_id value from uri segment 2. For example, when edit link is clicked for student_id 1, url generated is "http://localhost:8080/updateStudent/1" (See Routes.php later in this topic). $this->uri->getSegment(2) gives student_id. Then it calls model method getStudent() with the student_id as parameter to get the details of the student from database. Note that $uri instance is created in the constructor method of the controller.

Controller Method deleteStudent()

Method deleteStudent() is called by Ajax request when user clicks on Delete student link from the list of students. Let's see the code:

It calls deleteStudent() method of the model using student_id as parameter.

So, these were our controller methods, now let's see the Model in next step.

Step 4 - Write Model code (ModelStudent.php)

We have used three methods of the model; These are getStudent(), updateStudent() and deleteStudent(). So now let's see the code for these methods in the model. Keep ModelStudent.php in app/Models folder.

app/Models/ModelStudent.php

I have created database connection instance and we will be using query builder class. Our table name is student.

Method getStudent()

If student_id is blank, it selects all students from the table, but if student_id has a value, it selects data from student table for a student.

Method updateStudent()

This function takes two parameters, an array of values and student_id. This array has the column names of student table and input values. So, it updates the student table with the values for the specific student_id.

Method deleteStudent()

It takes student_id as parameter and deletes the row from the table for the specific student_id.

Database setup and other configuration changes are discussed in the next step.

Step 5 - Update Configuration files and Test the Application

Let us now update few setup files before we run the application.

We will update below files in Config folder and also, we will have .env file updated in the root directory. See below:

using ajax in codeigniter example

  1. Update config file (app/Config/App.php)

    Below is a section of App.php, set $baseURL and $index Page as given below:

  2. Update database setup file (app/Config/Database.php)

    As I mentioned before, I am using a database named 'demo' in localhost with user 'root', so below is our database connection setup in Database.php. Update $default as below:

  3. Update Routes file (app/Config/Routes.php)

    In Routes.php change default controller as student.

  4. Update .env to set the environment

    We need to set the environment to development in the environment (env) file. This file is in root directory.

    update data in codeigniter 4

    If you have not already copied env file to .env file, make a copy of env to .env. Open .env file in notepad and go to the line containing "# CI_ENVIRONMENT = production". Now copy this line and paste it as next line, then update the environment from production to development and remove # from the beginning of the line. See below:

Test The Application

You can test the application using built-in PHP server or you can use Apache web server if you are using xampp.

Test using PHP built-in server

Open command prompt and go to your CI4 project root. In my case it is D:/projects/student. Then type php spark serve and enter. This will start the server at port 8080.

codeigniter 4 update query with where condition

Now open the browser and run http://localhost:8080/. You will see the list of students page displayed as below:

update query in codeigniter 4

Verify that all the rows in student table are displayed in the page. Click on Edit link for any student and update the details of the student. Verify that update is done successfully. Also delete a student and see if the list is refreshed.

Test using Apache Web Server

If you are using XAMPP make sure your root folder is xampp/htdocs/student, i.e., you have to install CI4 in this folder. Open httpd-vhosts.conf file in notepad from xampp\apache\conf\extra folder.

how to update form data in codeigniter 4

Open the file in notepad and add below line at the end of it.

DocumentRoot "D:/xampp/htdocs/student/public"

Codeigniter update database record

Save it and restart the Apache service from xampp controller.

Now in app/Config/App.php, update base url as below:

Open the browser and run http://localhost. You will see the home page as displayed below:

codeigniter 4 updata data

Do the same testing described above.

That's it! Our development and testing are done for this CodeIgniter 4 application. Hope you could successfully develop and test it.

download source code to update and delete data in CodeIgniter 4Download Source Code

I have put codes for controller, model and view in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can use the code as is or you can modify them as per your requirements.

codeigniter 4 update databaseConclusion

This was a simple yet useful application in CodeIgniter 4 to update and delete record in MySQL database. There can be many uses of this type of application in our projects. I have used students as an example, it can be product or items or users. Hope this was useful for you.