• logo
  • PHP
  • PHP OOPs
  • script
    • JavaScript
    • JQuery
    • Ajax
    • AngularJs
    • VueJs
    • NodeJs
    • ReactJs
  • wordpress
  • Codeigniter
  • Codeigniter 4
  • Laravel
  • Python
  • MySql
  • Json
  • C
  • C++
  • More ...
    • Cakephp Framework
    • MongoDb
    • MySqli PDO
    • .htaccess
    • HTML 5
    • CSS
    • SEO
    • DCA

Codeigniter Tutorials

  • What is codeigniter?
  • Application_Architecture
  • MVC Architecture
  • HMVC Architecture
  • Codeigniter Configuration
  • Remove index.php from url in codeigniter
  • MVC Concept
  • View
  • Alternate PHP Syntax for View Files
  • Routing
  • Codeigniter URL
  • Get Current URL
  • Previous page URL get
  • Seo Friendly URL
  • Slug Create in codeigniter
  • What is _remap() function
  • Remove controller name from url in codeigniter
  • Codeigniter Controller Class
  • Class Constructor
  • GET $ POST method in Codeigniter
  • Models
  • Basepath, Apppath, FCPATH
  • URI Segment
  • Page Redirect
  • Helper class
  • Custom Helper class
  • Form Helper
  • Common Helper Functions
  • Common Function
  • Array Problems
  • Call controller in Helper
  • Add active class to menu using Helper class
  • Custom Library
  • Custom Library Example
  • when to use get_instance()
  • Codeigniter Hook
  • how to work inline css in codeigniter
  • Custom 404 page
  • 404 custom error page
  • Create custom config file in codeigniter
  • How to set and get config item value
  • How to Speed Up CodeIgniter App?
  • Codeigniter Functions
  • Session
  • cookies
  • How to Set & Get Tempdata in Codeigniter
  • flash messages in Codeigniter
  • Flashdata
  • Encryption and Decryption In CodeIgniter
  • Codeigniter security
  • csrf token form security
  • Password Hashing
  • Form Validation
  • Custom Validation
  • Registration Form with validation
  • Server Side Form Validation
  • Validate Select Option Field
  • Date Format Validation
  • Date Format change in codeigniter
  • Date Functions
  • DOB Validation
  • CI CRUD
  • User SignUp
  • User Login
  • User Logout
  • Login Account
  • Login form with RememberMe
  • Login Form with session
  • User change password
  • Change Password with Callback Validation to Check Old Password
  • Forgot password
  • Reset password
  • Insert data in database
  • Fetch data from database
  • Update data in database
  • Delete data in database
  • File Upload
  • Image Upload with resize Image
  • Upload Multiple file and images
  • Upload Multiple images with CRUD
  • File and image update
  • Upload Image Using Ajax.
  • Email Send
  • Email Send Using Email library
  • Email Send Using SMTP Gmail
  • Notification send
  • store data in json format in DB
  • Json parse
  • Fetch data Using Ajax with Json data
  • How to Show data Using Ajax with Json parse
  • Get JSON Data from PHP Script using jQuery Ajax
  • Insert data Using Ajax
  • Submit data Using Ajax with form validation
  • How to show data Using Ajax in codeigniter
  • Insert & Update Using Ajax
  • Registration Form With Validation Using Ajax in codeigniter
  • Delete data Using Ajax Confirmation
  • Delete All data Using checkbox selection
  • Ajax CSRF Token
  • Ajax Post
  • Ajax serverside form validation
  • Contact form using AJAX with form validation
  • DataTable Using Ajax dynamically
  • DataTables pagination using AJAX with Custom filter
  • DataTables AJAX Pagination with Search and Sort in codeigniter
  • DataTables in Codeigniter using Ajax
  • Ajax Custom Serarch
  • Ajax Live Data Search using Jquery PHP MySql
  • Ajax Custom Serarch and sorting in datatable
  • Dynamic Search Using Ajax
  • Autocomplete using jquery ajax
  • Jquery Ajax Autocomplete Search using Typeahead
  • Dynamic Dependent Dropdown Using Ajax
  • Dynamic Dependent Dropdown list Using Ajax
  • Dynamic Dependent Dropdown in codeigniter using Ajax
  • ajax username/email availability check using JQuery
  • Check Email Availability Using Ajax
  • Data Load on mouse scroll
  • Ajax CI Pagination
  • Pagination in codeigniter
  • Ajax Codeigniter Pagination
  • email exists or not using ajax with json
  • CRUD using AJAX With Modal popup in CI
  • Add / Show Data on modal popup using Ajax
  • Modal popup Validation using Ajax
  • Data show on Modal popup Using Ajax
  • Add / Remove text field dynamically using jquery ajax
  • How to Add/Delete Multiple HTML Rows using JavaScript
  • Delete Multiple Rows using Checkbox
  • Multiple Checkbox value
  • Form submit using jquery Example
  • REST & SOAP API
  • Multi-Language implementation in CodeIgniter
  • How to pass multiple array in view
  • Captcha
  • create zip file and download
  • PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
  • data export in excel sheet
  • Excel File generate in Codeigniter using PHPExcel
  • Dompdf library
  • tcpdf library
  • Html table to Excel & docs download
  • CI Database Query
  • Database Query
  • SQL Injection Prevention
  • Auth Model
  • Join Mysql
  • Tree View in dropdown option list
  • OTP Integration in codeigniter
  • curl post
  • download file using curl
  • Sweet Alert
  • Sweet alert Delete & Success
  • Log Message in Codeigniter
  • Menu & Submenu show dynamically
  • Set Default value in input box
  • Cron Jobs
  • Stored Procedure
  • Display Loading Image when AJAX call is in Progress
  • Send SMS
  • IP Address
  • Codeigniter Tutorialspoint
  • Website Link
  • How To Create Dynamic Xml Sitemap In Codeigniter
  • Paypal Payment Integration
  • Get Latitude and Longitude From Address in Codeigniter Using google map API
  • How To Create Simple Bar Chart In Codeigniter Using AmCharts?
  • dynamic Highcharts in Codeigniter
  • Barcode in Codeigniter
  • Codeigniter Interview Questions
  • Project
Home » Codeigniter » 

Delete Multiple Rows using Checkbox


File name : Delete_All.php

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

class Delete_All extends CI_Controller {


public function __construct() {
parent::__construct();
//$this->load->database();
}


public function index()
{
$data['data'] = $this->db->get("items")->result();
$this->load->view('delete_all_view', $data);
}


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."]);
}

}

delete_all_view.php

<!DOCTYPE html>
<html>
<head>
<title>how to delete multiple records using checkbox in codeigniter - itsolutionstuff.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.</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'),
url: $(this).data('<?php echo base_url();?>Delete_All/deleteAll'),
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>


Example 2 :-

Dekete Multiple Row Using checkbox with ajax

table :- users

CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Controller

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

class Users extends CI_Controller {

public function __construct(){

parent::__construct();
$this->load->helper('url');

// Load model
$this->load->model('Auth_model');

}

public function index(){

$data = array();

// Fetch all records
$data['users'] = $this->Auth_model->getUsers();

// Load view
$this->load->view('user-delete-checkbox',$data);
}

// Update rating
public function deleteUser(){

// POST values
$user_ids = $this->input->post('user_ids');

// Delete records
$this->Auth_model->deleteUser($user_ids);

echo 1;
exit;
}

}
?>

Model : Auth_model.php

// Fetch records
public function getUsers() {

// Users
$this->db->select('*');
$this->db->from('users');
$this->db->order_by("id", "asc");
$usersquery = $this->db->get();

$usersResult = $usersquery->result_array();

return $usersResult;
}

// Delete record
public function deleteUser($user_ids = array() ){

foreach($user_ids as $userid){
$this->db->delete('users', array('id' => $userid));
}

return 1;
}

View :- user-delete-checkbox.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Delete Multiple selected Records with jQuery AJAX in CodeIgniter</title>

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<!-- User List -->
<table border='1' width='100%'>
<thead>

<th>Name</th>
<th>Address</th>
<th>mobile</th>
<th><input type="checkbox" id="checkall" value='1'>&nbsp;
<input type="button" id="delete" value='Delete'></th>
</thead>

<tbody>
<?php
foreach($users as $user){
$id = $user['id'];
$address = $user['address'];
$name = $user['name'];
$mobile = $user['mobile'];
?>
<tr id='tr_<?= $id ?>'>
<td><?= $address ?></td>
<td><?= $name ?></td>
<td><?= $mobile ?></td>
<td align='center'><input type="checkbox" class='checkbox' name='delete' value='<?= $id ?>' ></td>
</tr>
<?php
}
?> </tbody>
</table>

<!-- Script -->
<script type="text/javascript">
$(document).ready(function(){

// Check all
$("#checkall").change(function(){

var checked = $(this).is(':checked');
if(checked){
$(".checkbox").each(function(){
$(this).prop("checked",true);
});
}else{
$(".checkbox").each(function(){
$(this).prop("checked",false);
});
}
});

// Changing state of CheckAll checkbox
$(".checkbox").click(function(){

if($(".checkbox").length == $(".checkbox:checked").length) {
$("#checkall").prop("checked", true);
} else {
$("#checkall").prop("checked",false);
}

});

// Delete button clicked
$('#delete').click(function(){

// Confirm alert
var deleteConfirm = confirm("Are you sure?");
if (deleteConfirm == true) {

// Get userid from checked checkboxes
var users_arr = [];
$(".checkbox:checked").each(function(){
var userid = $(this).val();

users_arr.push(userid);
});

// Array length
var length = users_arr.length;

if(length > 0){

// AJAX request
$.ajax({
url: '<?= base_url() ?>index.php/users/deleteUser',
type: 'post',
data: {user_ids: users_arr},
success: function(response){

// Remove <tr>
$(".checkbox:checked").each(function(){
var userid = $(this).val();

$('#tr_'+userid).remove();
});
}
});
}
}

});

});
</script>

</body>
</html>


Example : Delete multiple row using select checkbox.

Controller

File Name : Multiple_delete.php

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

class Multiple_delete extends CI_Controller {

function __construct() {
parent::__construct();

// Load user model
$this->load->model('Auth_model');
}

public function index(){
$data = array();

// If record delete request is submitted
if($this->input->post('bulk_delete_submit')){
// Get all selected IDs
$ids = $this->input->post('checked_id');

// If id array is not empty
if(!empty($ids)){
// Delete records from the database
$delete = $this->Auth_model->delete($ids);

// If delete is successful
if($delete){
$data['statusMsg'] = 'Selected users have been deleted successfully.';
}else{
$data['statusMsg'] = 'Some problem occurred, please try again.';
}
}else{
$data['statusMsg'] = 'Select at least 1 record to delete.';
}
}

// Get user data from the database
$data['users'] = $this->Auth_model->getRowsdata();

// Pass the data to view
$this->load->view('multipledelete', $data);
}

}

Model

File Name : Auth_model

// ####################### Multiple Delete ########################

$this->tblName = 'userstable';
// table name define in Auth_model constructor
function getRowsdata($params = array()){
$this->db->select('*');
$this->db->from($this->tblName);

//fetch data by conditions
if(array_key_exists("where",$params)){
foreach ($params['where'] as $key => $value){
$this->db->where($key,$value);
}
}

if(array_key_exists("order_by",$params)){
$this->db->order_by($params['order_by']);
}

if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}

if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
$result = $this->db->count_all_results();
}else{
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}

//return fetched data
return $result;
}

/*
* Delete data from the database
* @param id array/int
*/
public function delete($id){
if(is_array($id)){
$this->db->where_in('id', $id);
}else{
$this->db->where('id', $id);
}
$delete = $this->db->delete($this->tblName);
return $delete?true:false;
}

// ######################## End multiple delete ##################

View :-

File Name :

<!-- Display the status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="alert alert-success"><?php echo $statusMsg; ?></div>
<?php } ?>

<!-- Users data list -->
<form name="bulk_action_form" action="" method="post" onSubmit="return delete_confirm();"/>
<table class="bordered">
<thead>
<tr>
<th><input type="checkbox" id="select_all" value=""/></th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<?php if(!empty($users)){ foreach($users as $row){ ?>
<tr>
<td align="center"><input type="checkbox" name="checked_id[]" class="checkbox" value="<?php echo $row['id']; ?>"/></td>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['last_name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['phone']; ?></td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No records found.</td></tr>
<?php } ?>
</table>
<input type="submit" class="btn btn-danger" name="bulk_delete_submit" value="DELETE"/>
</form>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
function delete_confirm(){
if($('.checkbox:checked').length > 0){
var result = confirm("Are you sure to delete selected users?");
if(result){
return true;
}else{
return false;
}
}else{
alert('Select at least 1 record to delete.');
return false;
}
}

$(document).ready(function(){
$('#select_all').on('click',function(){
if(this.checked){
$('.checkbox').each(function(){
this.checked = true;
});
}else{
$('.checkbox').each(function(){
this.checked = false;
});
}
});

$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#select_all').prop('checked',true);
}else{
$('#select_all').prop('checked',false);
}
});
});
</script>








Itechtuto

Connect Us Socially:

Quick Links

  • itech
  • About Us
  • Feedback
  • Trademarks
  • Privacy Policy
  • Terms of Use
  • Sitemap
  • Trademarks
  • Privacy Policy
  • Terms of Use
  • Sitemap

Copyright © 2016 itechxpert (P) Ltd. All rights reserved.

Copyright © 2016 itechxpert (P) Ltd. All rights reserved.