YouTube Icon

Code Playground.

How to Delete Multiple Rows using Checkbox in Codeigniter 3?

CFG

How to Delete Multiple Rows using Checkbox in Codeigniter 3?

In this post, I would like to share with you how to delete multiple records using a checkbox in Codeigniter application. we will jquery ajax for remove multiple rows in CodeIgniter.

we always add delete button our listing page, but if you have thousands of records and you added some wrong rows data then it can take time to remove one by one row from a database table. So at that time if you add delete multiple records using checkbox then you have to just select checkboxes and remove at a time.

In this example, we will create "items" table with title and description column. Then we will simply add some dummy records. In the next, we will create two routes, one for listing items and another for ajax request. In listing page, we will display all items with a checkbox, then write code for delete selected items. When user will click on delete all button we will get selected checkbox ids and pass in ajax method. Then in ajax request, we will remove all records with that ids.

Just follow bellow few step and get example like as bellow preview.

Step 1: Create items table

In first step, you have to create one database and then we will create new new table "items" in database. You can use following SQL Query for create "items" table. So let's create using bellow SQL query:

Item Table:

CREATE TABLE IF NOT EXISTS `items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

Make sure, after created successfully table, add some dummy records so we can list out that.

Step 2: Add Routes

In this step, we need to create new routes for list items and ajax request. so open routes.php file and add code like as bellow:

application/config/routes.php

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


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


$route['item'] = "item";
$route['itemDelete']['post'] = "item/deleteAll";

Step 3: Create Item Controller

now, we have to create "Item" controller with index() and deleteAll(). so create item.php file in this path application/controllers/Item.php and put bellow code in this file:

application/controllers/Item.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Item extends CI_Controller {
 
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function __construct() {
       parent::__construct();
       $this->load->database();
    }
 
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index()
    {
        $data['data'] = $this->db->get("items")->result();
        $this->load->view('item', $data);
    }
 
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function deleteAll()
    {
        $ids = $this->input->post('ids');
 
        $this->db->where_in('id', explode(",", $ids));
        $this->db->delete('items');
 
        echo json_encode(['success'=>"Item Deleted successfully."]);
    }
 
}

Step 4: Create View File

In this step we will create item.php view file . In this file we will display all items with checkbox and write jquery ajax code. So let's update following file:

application/views/item.php

<!DOCTYPE html>
<html>
<head>
    <title>how to delete multiple records using checkbox in codeigniter - crowdforgeeks.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>how to delete multiple records using checkbox in codeigniter - crowdforgeeks.com</h2>
        </div>
    </div>
</div>
 
<button style="margin-bottom: 10px" class="btn btn-primary delete_all" data-url="/itemDelete">Delete All Selected</button>
 
<table class="table table-bordered" style="margin-top:20px">
 
  <thead>
      <tr>
          <th width="50px"><input type="checkbox" id="master"></th>
          <th>Title</th>
          <th>Description</th>
      </tr>
  </thead>
 
  <tbody>
   <?php foreach ($data as $item) { ?>      
      <tr>
          <td><input type="checkbox" class="sub_chk" data-id="<?php echo $item->id; ?>"></td>
          <td><?php echo $item->title; ?></td>
          <td><?php echo $item->description; ?></td>
      </tr>
   <?php } ?>
  </tbody>
 
</table>
</div>
 
<script type="text/javascript">
    $(document).ready(function () {
 
        $('#master').on('click', function(e) {
         if($(this).is(':checked',true))  
         {
            $(".sub_chk").prop('checked', true);  
         } else {  
            $(".sub_chk").prop('checked',false);  
         }  
        });
 
        $('.delete_all').on('click', function(e) {
 
            var allVals = [];  
            $(".sub_chk:checked").each(function() {  
                allVals.push($(this).attr('data-id'));
            });  
 
            if(allVals.length <=0)  
            {  
                alert("Please select row.");  
            }  else {  
 
                var check = confirm("Are you sure you want to delete this row?");  
                if(check == true){  
 
                    var join_selected_values = allVals.join(","); 
 
                    $.ajax({
                        url: $(this).data('url'),
                        type: 'POST',
                        data: 'ids='+join_selected_values,
                        success: function (data) {
                          console.log(data);
                          $(".sub_chk:checked").each(function() {  
                              $(this).parents("tr").remove();
                          });
                          alert("Item Deleted successfully.");
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });
 
                  $.each(allVals, function( index, value ) {
                      $('table tr').filter("[data-row-id='" + value + "']").remove();
                  });
                }  
            }  
        });
    });
</script>
 
</body>
</html>

Now we can check our example. You can also download full script of code.

I hope it can help you...




CFG