banner image
Sedang Dalam Perbaikan

CRUD Application with CodeIgniter and Bootstrap - Part 1



Now I think you have a clear understanding about using CodeIgniter framework. And I have explained about a CRUD application in a previous article. So, here I'm going to talk about how to create a system to create, retrieve, update and delete data with a web based system. I will use two frameworks including CodeIgniter for back-end and Bootstrap for front-end. Everyone can try this example easily and get the idea to handle data using PHP. This example is a student records system to add, view, update and delete details of students. Let's start!

Here you can see the screenshot of the system...

Add Student view


Stored Students view



Edit student view

Click here to download the source from GitHub.

I have already explained the way to configure CodeIgniter and Bootstrap. So I will not talk more about them. You can refer my previous articles. 
  • Download CodeIgniter from their site and extract them into a folder reserved for your project.
  • Download Bootstrap and extract those files also into a sub folder called assets in  the same project folder.
  • Then you have the project folder with the following file structure.



First you need to configure the basic files in CodeIgniter as usual, before start coding the application. Open the application folder and find autoload and database files in the config sub folder. Create a database as you want, to store data of the system and then configure it in database.php file. I created a table called users in the DB with 4 columns including student id(auto increment), student name, student regno and university. Give your DB name, user and password. Then move to the autoload file. Here I' m going to setup some basic things to to be kept enabled within the whole application.

Add the libraries :
$autoload['libraries']=array('database', 'form_validation','session');

Add the helpers :
$autoload['helper'] = array('url','form');

Next go to the routes.php file and set your default controller that you need to be loaded automatically. In my case it is called crud. Then this controller will always loaded automatically when you run the project in localhost.

$route['default_controller'] = 'crud';

Go to config.php file and give your base url for the project. That means the folder existing in htdocs folder including your project files. My project folder is CICRUD and here you will see my code.

http://localhost/Projects/CICRUD/

Now  you have to create the views to take inputs, view records and update records using Bootstrap. First take the UI for taking inputs. I will only take 3 inputs as you can see in the screenshots. So I have created my database to fulfill those requirements.

Now you will have a question about linking Bootstrap to HTML files. How to do it? It it the same way? 
No..But the same method is used...

As usual the link tag is used. But the way of referring the source is bit different. We use base_url( ) function in CodeIgniter. It will go like this...
<link href="<?php echo base_url() ?>assets/css/bootstrap.min.css" rel="stylesheet">
You have to echo the path first part with PHP since it is a PHP function. After you have given base url, the file is assumed to be in the main project folder. Then give the remaining path as the second part of the link. You can link the JS files in the way.

Now you are ready to go. Create the UI as you want. I have named it as "crud_view.php". Use Bootstrap Components and CSS from their site. Here: use this link to visit. Additionally I have linked a google font to make the font nice. You can refer here to get Google Fonts.
Remember to give names to the inputs as we want to call them later using these names.
Use form_open( ) and form_close( ) to declare the form for students. For form action, give your controller and method after we starting to code the controller file.

<!DOCTYPE html>
<html lang="en">
<head>
    <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>
</head>
<body>

<div class='container'>

<h1 class="heading" style="margin-top: 50px;">Welcome to CodeIgniter CRUD System</h1>

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

    <?php echo form_open('Crud/addStudent'); ?>
        <div class="form-group">
            <label for="regno">Student RegNo</label>
            <input type="text" class="form-control" id="sregno" name="stu_reg" placeholder="Type Student Registration number here...">
        </div>

        <div class="form-group">
            <label for="sname">Student Name</label>
            <input type="text" class="form-control" id="sname" name="stu_name" placeholder="Type Student Name here...">
        </div>
        <div class="form-group">
            <label for="suni">University</label>
            <input type="text" class="form-control" id="suni" name="stu_uni" placeholder="Type University here...">
        </div>
        <button type="submit" class="btn btn-primary">ADD STUDENT</button>
    <?php echo form_close(); ?>

    <?php echo form_open('Crud/viewUsers'); ?>
    <button type="submit" class="btn btn-info" style='margin-top: 20px;'>VIEW</button>
    <?php echo form_close(); ?>
</div>

<div class="col-md-6" style="margin-top: 60px; ">
    <!-- validation message for a successful submission -->
    <?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  } ?>

    <!-- validation messages for taking inputs -->
    <?php

    echo validation_errors('<div class="alert alert-danger alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span></button>','</div>');
    ?>

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

Arrange a space to validate errors and give success or failure messages. I used dismissible alert in Bootstrap to view the validation messages. Use it from their site. If you do not have idea about it, visit here to get some idea. When we hit the view button, the data should be retrieved from database and show. So there should be form to be submitted by the button reserved for view. 

Let's move to the controller setup. Its name is Crud. Create the index function to load the crud_view.php. Then create a function to load the users_view.php. These two functions are just loading the interfaces. users_view is the front end file that shows the records from database. Don't think about the showing results on this view. Just create the view and keep some space to display data fetched from database.

Next you have to create the function to add students.

public function addStudent() {

//validate  the data taken through the register form
$this>form_validation>set_rules('stu_reg','Student RegNo','required|is_unique[users.stu_reg]');
$this->form_validation->set_rules('stu_name','Student Name','required|is_unique[users.stu_name]');
$this->form_validation->set_rules('stu_uni','University','required');

if ($this->form_validation->run() == TRUE) {

    //load the model to connect to the db

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

    //set message to be shown when registration is completed

    $this->session->set_flashdata('success','Student is added');
    redirect('Crud');

 } else {

$this->load->view('crud_view');
 }

}

Here is_unique, required and valid are form validation rules. Use them to validate form. If validation is Ok, the Model should be loaded.  Model is the responsible person to insert data to the data for the controller function. Create a model called "Crud_model" and the the below piece of code to it to insert data.

    public function insertUser () {

        //insert data

        $data = array(

            //assign data into array elements

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

        );

        //insert data to the database

        $this->db->insert('users',$data);

    }

The  data that is inputted in the form is taken and stored in an array called data and then inserted to the database  table called users. Go back to the controller function and then you can see the insertUser function has been called after loading the model. Then we have to check whether the data has been inserted or not to the database. So we can set a flashdata message for the session. I used a message called success with the content of "Student is added". This message has been displayed above the adding  students form.


Then the view is redirected to load the index function of the controller. Since the index function is loaded by default, Only the controller name is included in redirection. If form validation becomes false, the the view which is used to enter the inputs is loaded back with the validation messages.

Move to the Crud_model and create a function to fetch data from DB.

public function getUsers() {

$this->db->select('*');
$this->db->from('users');
$this->db->order_by('stu_reg');
$query = $this->db->get();

        return $query->result();
}

Here, data are fetched looking at the student registration number. Records are ordered using stu_reg. This is the same SQL query written bit different. Finally this model function returns the array of the fetching results of the users. Again go to the controller file. Now we need to create a function to view users when someone hits the view button in crud_view.php file.

public function viewUsers() {

$this->load->model('Crud_model');
$records = $this->Crud_model->getUsers();
$this->load->view('users_view', ['records' => $records]);

}

Here we get the DB results from model and return them as an array to the users_view file to show the records. The results are assigned to the variable called records.  Then those results are passed to the view. If you want to show the results, it's compulsory to pass the data to the view. You can see the model function called getUsers has been called in this controller function; viewUsers.

Then move to the user_view.php file. I think you have already created it. My code will like this.

<!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="col-md-12">

<h1 class="heading" style="margin-bottom: 50px;">Stored users in Databse</h1>

<a href="<?php echo base_url('Crud') ?>"><button  class='btn btn-danger' style="margin-bottom: 50px;">Back</button></a>

    <table class="table table-striped">

        <tr>
            <th>Reg No</th>
            <th>Name</th>
            <th>University</th>
            <th>Edit</th>
            <th>Remove</th>
        </tr>

        <?php if (count($records)): ?>

            <?php foreach ($records as $row): ?>

        <tr>
          <td><?php echo $row->stu_reg; ?></td>
          <td><?php echo $row->stu_name; ?></td>
          <td><?php echo $row->stu_uni; ?></td>
          <th><a href="<?php echo base_url('Crud/editUser/'.$row->stu_id) ?>">
         <button type='submit' class='btn btn-warning'>Update</button></th></a>
         <th><a href="<?php echo base_url('Crud/deleteUser/'.$row->stu_id) ?>">
         <button type='submit' class='btn btn-danger'>Delete</button></th></a>
       </tr>

            <?php endforeach; ?>

        <?php else: ?>
            <p style="margin-bottom: 50px;">No users in the database</p>
        <?php endif ?>

    </table>

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

Here we have to use foreach loop to view the records. Using count, we check the records are there or not. If there are records, they are printed. Otherwise a message is shown as "No users in the database". Within the foreach loop, we have to take the result rows to view the data that we want. Here, row is a variable taken by me to assign the resulting rows. Then I took the data one by one and displayed in the table according to my format. In the above code, do not think about the code for update and delete buttons. For now, just place only the two buttons to view the options. I will explain them in the next part of this article. Using a table, we can align the data in a formatted way. 
Now you can go to the view called crud_view.php and give the form action for view button as;

<?php echo form_open('Crud/viewUsers'); ?>

Now when you click the view button, the results will be shown in crud_view.php file.

You are done with Creating and Retrieving data of this CRUD system. Next you have to deal with Updating and Deleting a particular user. So I'm planning to explain that part in the second part of this tutorial. Wait for it..Until try this and get a clear understanding on this section.
Good Luck!


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

No comments:

Powered by Blogger.