banner image
Sedang Dalam Perbaikan

CRUD Application with CodeIgniter and Bootstrap - Part 2



Welcome back to the tutorial of creating a CRUD application using Bootstrap and CodeIgniter. I think you have already read it. This is the second part of and here I will deal with Updating and Deleting data from the database. If you missed the previous article, visit here.

Part 1 link:  CRUD Part 1

I'm not going to repeat the same thing here and only the remaining part will be explained. Now you are OK with the adding and viewing options. In my design I have included two buttons to update and delete data of a particular user. Now I will explain how to perform these two options using PHP.

Update Student Record

If we want to update or delete a record we have to consider a special thing. That is the key of a record. That means username or user_id of a user. The specific data should be fetched from database. I use the user_id to get a particular user. First create the view to be loaded when update button is clicked to edit a user. In my case I will name it as edit_user.php. Place a form to get the input fields that are needed to be updated. Another important thing comes here because when we go to update, the already available data should be shown in an editable way. Just look at the code for interface. Form actions will be explained later.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CRUD | CodeIgniter</title>
<link href="<?php echo base_url() ?>assets/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<style type="text/css">
    body{
        font-family: 'Lato', sans-serif;
        margin: 0;
        font-size: 18px;
    }
</style>
<body>

<div class='container'>

<h1 class="heading" style="margin-top: 50px;">Edit user</h1>

<div class="col-md-6" style="margin-top: 30px; ">

    <?php echo form_open('Crud/editUser/'.$row->stu_id); ?>

            <div class="form-group">
            <label for="sid">Student ID</label>
            <input type="text" class="form-control" id="sid" name="stu_reg" value="<?php echo $row->stu_id ?>" readonly>
            </div>
            <div class="form-group">
            <label for="regno">Student RegNo</label>
            <input type="text" class="form-control" id="sregno" name="stu_reg" value="<?php echo $row->stu_reg ?>">
            </div>
            <div class="form-group">
                <label for="sname">Student Name</label>
                <input type="text" class="form-control" id="sname" name="stu_name" value="<?php echo $row->stu_name ?>">
            </div>
            <div class="form-group">
                <label for="suni">University</label>
                <input type="text" class="form-control" id="suni" name="stu_uni" value="<?php echo $row->stu_uni ?>">
            </div>


    <button class='btn btn-success' name='update' style='margin-bottom: 10px;'>Update</button>
    <?php echo form_close(); ?>

    <a href="<?php echo base_url('Crud/viewUsers') ?>"><button type='submit' class='btn btn-danger'>Back</button></a>

</div>

<div class="col-md-6" style="margin-top: 60px; ">

<?php if ($this->session->flashdata('success')): ?>
        <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <?php echo $this->session->flashdata('success'); ?>
        </div>
    <?php elseif ($this->session->flashdata('error')): ?>
        <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <?php echo $this->session->flashdata('error'); ?>
        </div>

    <?php else: ?>
<?php endif; ?>

</div>

    <script src="<?php echo base_url() ?>assets/js/jquery.min.js"></script>
    <script src="<?php echo base_url() ?>assets/js/bootstrap.min.js"></script>
</body>
</html>

Look at the values given for the input fields. Those are with PHP codes that echo the available data of a user. They are taken from the ongoing session. You will remember that I have used two variables called records and rows in previous article. So, for a row, relevant value has been fetched from DB here. The following code piece does this job. For every data, this part should be included.

<?php echo $row->stu_name ?>

In this view, I have placed another section for validations; for flashdata messages as I did in the previous article. One for the errors and the other one for the success actions. You will see the content of these messages later. Back button is assigned to load the crud_view file again. That's why I created a controller function to load just the view on the previous day.

Move to the crud_view and there I had included a coding part for two buttons created  for updating and deleting data. Let's move to these buttons.


In the form, I have included a form action ;
          'Crud/editUser/'.$row->stu_id

Crud is my controller and the editUser is my function in it. This function should be called when the update button in the users_view.php file.
For the button links I have given the controller and method with an id. This is the particular id I have used to refer a single record. It has been connected to the method with a dot mark. If you click on update or delete button, then you will be directed to a URL with an id. Look here.



Here, editUser is my controller function and as I clicked on the update button reserved for the user with id 1, the URL is giving the id as 1.

Look at the model function for editing a user data.

    public function edit($stu_id) {

        $this->db->where('stu_id',$stu_id);
        $query = $this->db->get_where('users', array('stu_id' => $stu_id));

        return $query->row();

    }

What is it doing? I have given the user_id as a parameter to the function as ID is the field that is required to execute this function. At the end of this function, the relevant data of the user having the unique ID is fetched from database table; users. Then his records are returned as an array. Now we have to take the newly entering data and send them to the database using another model function. Let's see it. I will create a function called update.

    public function update($stu_id) {

        $data = array(
        'stu_reg' => $this->input->post('stu_reg'),
        'stu_name' => $this->input->post('stu_name'),
        'stu_uni' =>$this->input->post('stu_uni'),

        );
        $this->db->where('stu_id',$stu_id);
        $this->db->update('users',$data);
        return $stu_id;
    }

Here, the entered data are taken and stored in an array called data. Then these data are matched with the user_id and update the database records accordingly. Finally the particular user's id is returned. Now we can move to the controller function to update these records.

public function editUser($stu_id) {

$this->load->model('Crud_model');

if (isset($_POST['update'])) {

if ($this->Crud_model->update($stu_id)) {

$this->session->set_flashdata('success','Student is updated');
redirect('Crud/editUser/'.$stu_id , 'refresh');

} else {
$this->session->set_flashdata('error','Student is not updated');
redirect('Crud/editUser/'.$stu_id , 'refresh');
}
}

$data['row'] = $this->Crud_model->edit($stu_id);
$this->load->view('edit_user',$data);

}

In the updating view, there's a button to update the data after the changes are done. In this function, first Crud_model is loaded. Then check for that button  for a submission. If something is submitted, then update function is loaded to perform; not the function;edit. Because edit functions is not doing the updating job. It is the function which gets the correct data according to the calling user_id. If the function-update is executed, the data should be updated. So I have set a flash message as usual, to check whether the job is done or not. If it is done, message will be shown as "Student is updated" and otherwise the message "Student is not updated" will be displayed.

After the both messages, redirection is done according to the particular user. Remember to call the controller function to load back the edit page with the user_id. When we come out of the if clauses, there are two lines of code. They are to load the edit_user view with the data fetched by edit function in the Crud_model.
 We have now completed updating operation for a user in the system. Then we have to do the final operation of this CRUD tutorial. It is the easiest one.

Delete Student Record

This is so easy. One model function is needed to delete the data and one controller function is needed to call this model function. 

Model function :

    public function delete($stu_id) {

        $this->db->where('stu_id',$stu_id);
        $this->db->delete('users');
   }

This function is simply delete the data of any user matched with the taken user_id. The table; users will not have the data record called with the id, any more.

Controller function :

public function deleteUser($stu_id) {

$this->load->model('Crud_model');
$this->Crud_model->delete($stu_id);
redirect('Crud' , 'refresh');
       
}

The controller function is called by the button in the users_view.php file. Then the controller function calls for the model and its relevant function with the user's id; here it is delete. After the deletion, the view is redirected to the index view.
Now you completed Deleting operation.

So, all 4 main CRUD operations are explained with these two articles. I tried my best to explain. It is not easy to explain word by word. So I did explanation to some extent.

Hope you will get the idea and will try to be familiar with both Codeigniter and Bootstrap.
Frameworks cannot be mistaken with the current level of web development field. So, get used to them. If you have any question, drop a comment.
Good Luck!







CRUD Application with CodeIgniter and Bootstrap - Part 2 CRUD Application with CodeIgniter and Bootstrap - Part 2 Reviewed by DAL on September 16, 2017 Rating: 5

No comments:

Powered by Blogger.