Digging into the ways to delete multiple records in codeigniter

Sharad Jaiswal
Written by Sharad Jaiswal

Posted On: Apr 17, 2019

 

CodeIgniter is a lightweight powerful open source PHP web application framework that provides a simple and elegant platform to create full-featured web applications without the overhead of having the costly build  reusable components

CodeIgniter is being widely used because it is loosely based on the popular model-view-controller (MVC) development pattern. Being large and easy to understand, it has got a large and active user community thus, making it the second among the most popular framework. Some features that make it an extremely popular choice include:-

  • It is so easy and a hassle-free process to migrate from one server hosting to another making it a popular choice among the users of web development.

  • It has a small footprint means it is lightweight and has very little overhead which means it lends itself towards fast performance especially when it is compared to the other frameworks.

  • It's also easy to get going as it requires no configuration or a very little one.

Sometimes, we do have inaccurate or obsolete data that needs to be deleted for making access to our database faster and easier for further use. For instance, moving data from the previous year’s calendar to another set of current years tables. This can be done faster if we have moved or deleted the unwanted or inaccurate data thus, reducing the business costs involved too.

To have a hassle free deletion of multiple records in CodeIgniter we can use the checkbox method.You have got two ways:-

  • Either you can select each checkbox of the record which is to be deleted.

  • Or you can select /Deselect all checkboxes to check or uncheck all rows at once and get them deleted in just one go.

The Steps needed to do the upward process of deleting multiple records in just a few seconds from a database in CodeIgniter are:-

  • Taking out all the user data from MYSQL database and putting them together in an HTML table.

  • To Select, multiple records append checkbox with each of them.

  • To Select or deselect all records at one go, affix a checkbox in the table header.

  • To remove all checked rows in the MYSQL database, do include Delete button.

Let's see how the whole process works

  • The first process involves the creation of a database table to store the data of the user.SQL creates table In the MYSQL database using the following steps and commands

The code can be like:-

CREATE TABLE `users` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

`last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

`email` varchar(200) COLLATE utf8_unicode_ci NOT NULL,

`phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,

`created` datetime NOT NULL,

`modified` datetime NOT NULL,

`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Deactive',

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller (Users.php)

The two functions from the users control Construct ( ) and Index ( ) are used further.

  • Construct( ) is used to load the user model.

  • Index( ) is used

  • To fetch data from the database using the get Rows() function.

  • To load the data of the user for viewing.

  • If the user wants to delete the rows and the request is submitted

  • Fetch the ID of the rows to be deleted using the $_POST in PHP.

  • To check the ID array should not be empty.

  • Using the Delete( ) function to delete the selected rows as mentioned in ID array.

  • And finally giving the message to view.

And the code for it can be like:-

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

class Users extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        
        // Load user model
        $this->load->model('user');
    }
    
    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->user->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->user->getRows();
        
        // Pass the data to view
        $this->load->view('users/index', $data);
    }
    
}

Model (User.php)

The database related works are done in this model like as:- Construct ( ), get Rows( ) and delete( ).

<php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Model{
    
    function __construct() {
        $this->tblName = 'users';
    }
    
    /*
     * Fetch posts data from the database
     * @param id returns a single record if specified, otherwise all records
     */
    function getRows($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;
    }
    

View (users/index.php)

To see the delete confirmation dialog and integrate all checkboxes functionality jQuery is needed and must be included in the library.

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

Delete confirm ( ) is used to check if at least a box has been checked and further giving an alert message if the record definitely wants to be deleted.

Select /Deselect ( ) all the checkboxes in one go using the jQuery.

<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>

The user can select /Deselect multiple rows and accordingly can delete the multiple records in the CodeIgniter application.

  • First, the data is fetched from the database.

  • Then multiple rows to be deleted are selected.

  • To check/uncheck all checkboxes, the checkbox is selected under the table header.

  • A dialog for confirming the delete appears when the delete button is clicked.

  • Selected records are deleted after the confirmation process.

<!--- 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>

Conclusion

As every database carries the number of records and if the user wants to delete the one – one row at a time, it can be a cumbersome task and would involve a lot of time with more number of errors.

To save your time and make the code more user-friendly, multiple deletions of records from multiple rows is an excellent process to be included in the CodeIgniter application and this can be incorporated using the checkbox method.

    Please Login or Register to leave a response.

    Related Articles

    Blog

    An Introduction to Serverless Databases Architecture

    Understanding the Serverless Architecture: The serverless computing is a cloud computing execution model which means that the cloud provider is managing the distribution of computer resources dynamica..

    Blog

    JSON Vs XML

    JSON Vs. XML: SON and XML both are used for storing and carrying data on the web.XML was originally developed as an independent data format, whereas JSON was developed specifically for use in the web ..

    Blog

    What are difference between React Native and NativeScript?

    Both React Native and NativeScript are amazing frameworks. Both frameworks are part of the new generation cross-platform mobile frameworks that are NOT using the browser to package it into Native app...

    Ask a Question