CodeIgniter Part 2: Understanding MVC Pattern Using SignUp and Login

in #utopian-io6 years ago (edited)

uderstanding-MVC-pattern-using-signup-and-login-main.jpg

Repository

CodeIgniter Github Repository

Previously we were able to go through the entire process of setting up a CodeIgniter project from scratch which will serve as a base for starting up a new project, we will be using the initial setup we did, to continue as I walk you through the MVC pattern using a Sign Up and Login form and the data flow across model, view, and controller

Level of Difficulty
Basic

What you will learn:

  1. How to set up various routes (the url addresses that users will use to access various components of the application) using the controller.
  2. How to process data from the database and pass to controller using the model
  3. Rendering views with required data or components through the controller
  4. Query processing techniques to send or retrieve data from database

Requirements:

  1. A good knowledge of PHP OOP programming
  2. Knowledge of database administration tools (I will be using phpMyAdmin in this tutorial for MySQL database administration).
  3. Understanding of HTML, CSS and BOOTSTRAP( not a primary requirement since our focus here is on the MVC flow pattern)

Getting Started:

Note: we will be referencing our initial setup project for all url addresses which is localhost:81/firstproject
Before getting into the project, lets understand how the MVC pattern works.

mvc-flow.jpg

How it works:

• User visits our site and requests for information by typing a url address on the address bar, for example in our local project localhost:81/firstproject/Login this is a controller call
• The controller checks if the request requires data to be served
• If data is required, It will request for this information from the model
• The model then processes the data by connecting to the database and then returns the data as requested by the controller.
• The controller then sends the response back to the user through the appropriate view.
• If data is not required then the controller will simply respond to the use with the desired view.

The MVC flow in Action:

Before we start building the application, let’s identify the url components of an MVC application, this will make it clearer when we start the routing process.

Case1: localhost:81/firstproject/
base-controller.jpg
From the above you can see that only the site name is used no controller is mentioned in this case the application will called the base controller (the controller to be called when a user initially enters your site url) which is normally configured in the config file, we will do this as we progress.
If we deploy our app on live server then the user will enter the address as www.firstproject.com and automatically it will call the base controller we’ve configured.

Case 2: localhost:81/firstproject/Login
In this case the user has explicitly specified the controller which is the first segment of the url.
On live environment this url will look like this: www.firstproject.com/Login , what each url segment of the mvc application actually stands for.
Let’s use a more broader url and explain each segment
www.firstproject.com/Users/create_user/id
url_segment.jpg
The url segments from 3 and above specifies the arguments that can be passed to a method or action in a controller.

Building the application

Approach:

For every application development, it is advisable t use an approach towards the development flow, here I will be using the following approach.
• Identify the controllers
• Design the corresponding views as specified in the controllers
• Following the views design the database
• Build the corresponding models in relation to the database and the required data from the views.
For this applications, the following will be required

1. Controllers

i. Home: This will be the base controller, and it will have just an index method which will render the first view of the application, the index method of every controller is the action that is called once the controller is loaded if you do not specify any other method in the url.
ii. Login: This will be used to load the login view, it will also content only an index method which will render the login view
iii. Signup: Used to load the signup view, it equally has only the index method to render the signup view.
iv. Users: This will be used to perfom various users activities, I will contain login , createUser and logout method.
Notice the naming convention of the controllers: it is advisable to Start each controller name with an upper case character, this is because when you deploy your application to a live environment, Ci- has been built in such a way that some servers only see controllers which start with uppercase characters to avoid breaking of urls make sure each controller starts with an upper case character.

2. Views:

i. main: This will serve as the layout in which other views will be loaded, this will help us to avoid loading repeated components of our application again and again like the header, footer and sidebars. It holds every component that will be visible to all other views, all we need do is to load each view when called on the content section of this view.
main-layout.jpg

**ii. home: **This is the view that will be displayed, once a user successfully logs into the application.
home_view.jpg

iii. sign_up: this view will be used to enable the user to sign up into our application
signup_view.jpg

iv. login: this will provide the users the interface to Login into the application.
login_view.jpg

3. Database Schema.

Now that we have all our views, you can notice that looking at the login and signup forms all we need in our database is the uses username and password.
I won’t be going into the details of how to create the database and the tables but I will give you the required information to enable you create the database and the table.
Using your preferred database administrative tool.
• Create a new database: for the purpose of this tutorial I have called the database ci-mvc
• Run the scrippt to create the users table: Once you have created the database, click on the sql command and run the following script:

                     CREATE TABLE `users` (
                     `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
                     `username` varchar(255) NOT NULL,
                     `password` varchar(255) NOT NULL
                   ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

This will create a table in the ci-mvc database called users
You should be familiar with the above script, as this is one of the requirements for this tutorial, but feel free to ask were you feel you are not clear enough.

4. Models:

Now that we have our views and database set, we have few things in mind to help us create our models, these are;
• How to save a user’s details into the database upon sign up
• How to check if the user’s details are already in our database to avoid duplicate entries
• How to login the user upon sign up

With these in mind we can now have the following models
1. User_model: this will contail two methods
i. login_user: used to create the logic to enable the user login to the system successfully
ii. create_user: used to register the user into our database.

2. Authentication_model: This will contain just one method.
i. validate_user: this will be used to check whether the user is already in the databse during signup.

Now that we have all the components of our application identified, let’s get to work.

Connect the application to our new databse:

Got into the database file in the config folder of the development environment and add the required database credentials as shown below:
databse-config.jpg

Change the hostname, username, password to match with yours, as you can see I’ve specified the database we created ci-mvc, with this we can call any table in this databse as codeigniter will automatically do the connection.
Now we can create our controllers, views are models.

Controllers

1. Home.php

<?php

if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}

class Home extends CI_Controller{

public function __Construct() {
    parent::__Construct();
    if(!$this->session->userdata('logged_in')) {
      redirect(base_url('Login'));
    }
}
public function index(){
    $data['main_content'] = 'home';
    $this->load->view('layouts/main',$data);
        
}

}
?>

This first line:
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
Is used to prevent direct access to our scripts, this is strongly advisable which is a security measure in CI to avoid users running our scripts when not needed. For example a user should not be able to access this path directly: www.firstproject.com/applications/controllers/Home.php

For the second section:
The first line:
class Home extends CI_Controller{
is used to extend the CI core controller class, this is required for every controller,

The second line contains the constructor, the constructor serves as the first state of the application, so if there is anything that needs to be done before the index method gets called, you have to specify it in the constructor.
I have added comments in the controller methods to help you understand what each section is doing.

class Home extends CI_Controller{
    public function __Construct() {
        parent::__Construct(); // initialize the parent constructor
        if(!$this->session->userdata('logged_in')) {// on arrival on the application redirect the user to the login page if not already logged in
          redirect(base_url('Login')); //base_url('Login') will be localhost:81/firstproject/Login
        }
    }
    public function index(){
        $data['main_content'] = 'home'; //assign the home view into a variable called data 
        $this->load->view('layouts/main',$data);//and load it in the main content, in our case we are loading it into the main layout
            
    }

}

From the above, once the home controller is call, it will first call the constructor which will check whether the user is logged in or not using the session variable, if logged in it will go to the index method and load the home view into the main layout content section, Once we get to the main layout view you will understand this better.
If you understood this well enough then you can easily create the others as they all follow the same pattern.

2. Signup.php

Read through the comments as it take same flow like the home controller

<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Signup extends CI_Controller{
    public function __Construct() {
        parent::__Construct();
        if($this->session->userdata('logged_in')) {// if a user is already logged in and tries to access this controller he will be directly redirected to the homepage
          redirect(base_url());
        }
       } 

    public function index(){
        $data['main_content'] = 'Users/sign_up';//assign the Signup  view into a variable called data
        $this->load->view('layouts/main',$data);//and load it in the main content of the layout view
        
    }

}
?>

3. Login.php

Same applies here:

<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Login extends CI_Controller{
    public function __Construct() {
        parent::__Construct();
        if($this->session->userdata('logged_in')) {// if a user is already logged in and tries to access this controller he will be directly redirected to the homepage
          redirect(base_url());
        }
    }
    public function index(){
        $data['main_content'] = 'Users/login'; //assign the Signup  view into a variable called data
        $this->load->view('layouts/main',$data);//and load it in the main content of the layout view
        
    }

}
?>

4. Users.php:

this controller has three methods login, createuser and logout.

i. login

public function login(){
        $this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean'); //form validation from codeigniter validation methods
        $this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[50]|xss_clean');//form validation from codeigniter validation methods
        if($this->form_validation->run() == FALSE){//to check if the form validation rules where successful or not

            $data['main_content'] = 'Users/login';
            $this->load->view('layouts/main',$data);
        } else{
            //Get from post
            $username = $this->input->post('username');// enable us to get the posted username by the user into the variable $username
            $password = $this->input->post('password');// enable us to get the posted password by the user into the variable $password
            
            //Validate user
            if($this->User_model->login_user($username,$password)){
                //cretate array of user data to store in a session
                $user_data = array(
                    'username'   => $username,
                    'logged_in'  => true
                    );
                //Set session userdata
                $this->session->set_userdata($user_data);
                //set success message
                $this->session->set_flashdata('login_success','You are now logged in');
               redirect(base_url());
                
            } else{
                //Set error
                $this->session->set_flashdata('login_failed','Sorry, Your Login Information is invalid');
                redirect(base_url(' Login'));
            }
                
        }

    }

I’ve included some comments for a clearer understanding but, let me explain some of the code snippets here.
The part as shown below, usese the codeigniter form validation methods to check if the form was properly filled or not, this form validation, form processing and security will be covered in more in-depth in the next tutorial, let’s focus more on how the controller interacts with the model.

$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean'); //form validation from codeigniter validation methods
        $this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[50]|xss_clean');//form validation from codeigniter validation methods
        if($this->form_validation->run() == FALSE){//to check if the form validation rules where successful or not

            $data['main_content'] = 'Users/login';
            $this->load->view('layouts/main',$data);

To access a model you have to either auto load the model or load it in the controller constructor method as follows:

  $this->load->model(‘modelname’);

I usually prefer uato loading all models so I can call them from any part of the project, once you’ve auto loaded a model then u can call it using $this keyword. As have done here

$this->User_model->login_user($username,$password)

But before here we’ve already saved the posted username and password of the user into the two variables $username and $password, we then pass these values to User_model and clearly stating the method we want it to process i.e ** login_user** method in the User_model.

If the model successfully processes the data then we will set the session variables of the user to enable us track his movement across the application. This is achieved using the Codeigniter session methods as **session->set_userdata($user_data) **method, the $user_data will contain the values you intend to set as session variable, it can be a single value or an array of values as in our case. After setting the session we can then set a message to be displayed to the user on the home view using the method session->set_flashdata(‘prefered-variable’,’message to be displayed to the user’).
Below is the code for this

//Validate user
            if($this->User_model->login_user($username,$password)){
                //cretate array of user data to store in a session
                $user_data = array(
                    'username'   => $username,
                    'logged_in'  => true
                    );
                //Set session userdata
                $this->session->set_userdata($user_data);
                //set success message
                $this->session->set_flashdata('login_success','You are now logged in');
               redirect(base_url());
                
            } else{
                //Set error
                $this->session->set_flashdata('login_failed','Sorry, Your Login Information is invalid');
                redirect(base_url(' Login'));
            }

As you can see from the above code, we’ve set two variables login_success and login_failed with corresponding messages to be shown to the user, if the login is successful it will redirect the user to the home page were the login_success message will be displayed that’ why I’ve used this;
php redirect(base_url());

On the other hand if the login fails then the login page will be loaded again with the login_failed message displayed for the user to re-try.

ii. createUser:

This same flow is repeated for the createUser method apart from were we need to check if the user already exists in the database by calling the validate_user method of the Authentication_model before calling the create_user method of the User_model to actually create the user.
Here is the complete code for the createUser with comments to enable you understand it better.

public function createUser(){
        $this->form_validation->set_rules('username','Username','trim|required|max_length[20]|min_length[4]|xss_clean');
        $this->form_validation->set_rules('password','Password','trim|required|max_length[20]|min_length[4]|xss_clean');
        $this->form_validation->set_rules('password2','Confirm Password','trim|required|max_length[50]|min_length[4]|xss_clean|matches[password]');

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

            $data['main_content'] = 'Users/sign_up';
            $this->load->view('layouts/main',$data);

        } else {
            
             $postData = $this->input->post();
             $validate = $this->Authentication_model->validate_user($postData);//call the Authentication_model method to validate if the user already exists
             $enc_password = md5($this->input->post('password'));//encrypt the user password using md5 encryption
            
             $data = array(// set an array of values of the username and encrypted password to be sent to the user_model to create the user
            'username'              =>$this->input->post('username'),
            'password'              =>$enc_password
            );

             if ($validate) {//from the result gottenfrom the Authentication_model check if the user already exists before even calling the  user_model to create the new user
                $this->session->set_flashdata('user_exist','A user with those credentials already exists kindly review and try again');
                redirect(base_url('Signup'));//if the user exists then reload the signup page and display the error message
             }else{
                if ($this->User_model->create_user($data)) { //if the user doesn't exist then call the user_model to create the new user

                $this->session->set_flashdata('user_signup','Sign Up Successful Kindly login');
                redirect(base_url('Login'));
            }
            else{
                $this->session->set_flashdata('user_signup_error','unable to save your details try again');
                redirect(base_url('Signup'));

            }
           }
            

        }
    }

iii. logout:

Once a user successfully logs into the system we created some session variables to keep track of the user this is mainly to enable us show only the data related to that particular user at any given time, once the user clicks on the logout link, this method will be called. It’s duty is to clear up the user session variables, Codeigniter has special methods to enable us achieve this easily.
The first methos is ** session->unset_userdata(‘variable to unset’) ** and session->sess_destroy() to finally destroy the session. See code below.

public function logout(){
        //Unset session data
        $this->session->unset_userdata('logged_in');
        $this->session->unset_userdata('username');
        $this->session->sess_destroy();

        //set logout message
            $this->session->set_flashdata('logged_out','You have been logged out');
           redirect(base_url());
        

    }

By now your controllers directory should have all the controllers in it as seen in mine below:
Controllers.jpg

Before moving to the models, lets auto load the components we’ve used in the codes above. We’ve already stated the Models we will be needing although we haven’t created them, let’s auto load them and other libraries so that once they are created we can easily access them.
Open up you autoload.php in config folder. as shown below;
autoload.jpg

1. Libraries

Go to line 61 it might be a different line in your editor, but find this line of code.
php $autoload['libraries'] = array();
And replace it with
php $autoload['libraries'] = array('database','session','form_validation');
This will auto load the code igniter core functionalities for databse, session and form validation as we have used in our project.

2. Helper:

Replace this line of code on line 91
php $autoload['helper'] = array('url','form');

With the below code
php $autoload['helper'] = array('url','form','html','security');
This will facilitate all html entities and security measures we will use in our data processing, more will be discussed on this when we be learning form processing and security.

3. Model:

Trace this line of code, usually at the end.
php$autoload['model'] = array();
And replace it with
php $autoload['model'] = array('User_model','Authentication_model');

Now we have our User_model and Authentication_models accessible in our application we don’t have to load them in each controller constructor methods.

The Default controller:

Let’s also specify that the Home controller should be the first controller to be called. Still in the config folder click on the routes.php file.default_contoller.jpg

You can see the 3rd to last line has clearly specified that the default controller should be welcome, this was the controller being called in our initial setup, Change this to now call our home controller, as follows:
php$route['default_controller'] = 'Home';

This will call our home controller on initial launch of the application

Views

Our views will be structured in this format
Create two sub-folders called Layouts and Users
Inside Layouts create one file main.php
Inside Users create two files login.php and sign_up.php
Create one root file called home.php
this structure is to enable our views to be categorized in there respective sections so that as the application grows additional views will be easily added to their respective sections.
Your views folder should now look like this.
Views.jpg

1. Main.php

This contains the main application layout where other views will be loaded, for larger applications you can have more than one layout, say one for the main landing, page and one for the dashboard, so each layout will represent a major view of the application.

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>School Management System</title>
      (html comment removed:  Latest compiled and minified CSS )
      <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/bootstrap/css/bootstrap.min.css"/>
      <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/bootstrap.css"/>
      <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/custom.css" />
      <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   </head>
   <body>
      <nav class="navbar navbar-inverse">
         (html comment removed:  Brand and toggle get grouped for better mobile display )
         <div class="container">
            <div class="navbar-header">
               <a class="navbar-brand" id="logo" href="<?php echo base_url(); ?>"><img src="<?php echo base_url(); ?>assets/images/codeigniter.png" class="img img-responsive logoImage"></a>
               <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
            </div>
            (html comment removed:  Collect the nav links, forms, and other content for toggling )
            <div class="collapse navbar-collapse">
               <ul class="nav navbar-nav  menu" id ="menu">
                  <?php if($this->session->userdata('logged_in')) : ?>
                  <li><a href="<?php echo base_url('Users/logout'); ?>" class="active">Logout</a></li>
                  <?php endif; ?>
               </ul>
            </div>
            (html comment removed:  /.navbar-collapse )
         </div>
         (html comment removed:  /.container-fluid )
      </nav>
      <div class="container" style="margin: 0 auto;">
         <div class="row">
            
            <div class="col-md-12">
               (html comment removed: MAIN CONTENT)
               <?php $this->load->view($main_content); ?>   
            </div>
            (html comment removed: /span9)
         </div>
         (html comment removed: /row)
         <hr />
         <footer>
           
         </footer>
      </div>
      (html comment removed: /fluid-container)
   </body>
</html>

The code here is just html with little php embedded in it. I want to explain two important sections here

One

<ul class="nav navbar-nav  menu" id ="menu">
                  <?php if($this->session->userdata('logged_in')) : ?>
                  <li><a href="<?php echo base_url('Users/logout'); ?>" class="active">Logout</a></li>
                  <?php endif; ?>
               </ul>

This code is used to hide or show the logout link depending on the user’s state. If the user’s session variable logged_in is set it means the user has successfully logged, In this case show the logout link otherwise hide the link, this is one of the reasons why we needed to set session variables for the logged in user.

Two

<div class="col-md-12">
               (html comment removed: MAIN CONTENT)
               <?php $this->load->view($main_content); ?>   
            </div>

This little code is the most important in this main layout view, it is responsible for rendering the views sent through the main content from the controller, if you can recall what we did when a controller’s index method is called, the method will store a view in the main_content inside a data variable, let’s just see this again:
Using the Home controller index method.

       public function index(){
        $data['main_content'] = 'home'; //assign the home view into a variable called data 
        $this->load->view('layouts/main',$data);//and load it in the main content, in our case we are loading it into the main layout
            
    }

from this you can see that the $data variable holdes the main content which is the home view this is then passed to the main layout to be rendered. Through this line:
php $this->load->view('layouts/main',$data);

2. Home.php

This contains the code to display the home content to the user on successful login and also the messages to be shown.

<?php if($this->session->flashdata('login_success')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('login_success');?></p>
<?php endif; ?>
<div class="home-div text-center" style="width:100%">
               <h1>CodeIgniter MVC Pattern</h1>
               <p>A simple codeIgniter application to demonstrate MVC flow pattern</p>
               <hr/>
            </div>
   <h2 class="text-center home-text">Welcome to our awesome app</h2>

The first line contains the message to be displayed if login is successful as define in the login method of the Users controller, we earlier specified that if login is successful then set a session flashdata called login_success This is what will be displayed here.

<?php if($this->session->flashdata('login_success')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('login_success');?></p>
<?php endif; ?>

Through this same process, you can also define variables of data gotten from the models and directly display them here in the view

3. login.php

This has same structure as the home.php with messages to be displayed at each users actions.

<div class="well middle-form">
  <?php if($this->session->flashdata('user_signup')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('user_signup');?></p>
<?php endif; ?>
<?php if($this->session->flashdata('login_failed')) : ?>
  <p class="alert alert-dismissable alert-danger text-center"><?php echo $this->session->flashdata('login_failed');?>check your details and Try to Login again</p>
<?php endif; ?>
<?php if($this->session->flashdata('logged_out')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('logged_out');?></p>
<?php endif; ?>
<h3>Login</h3>
<?php echo validation_errors('<p class="alert alert-dismissable alert-danger">'); ?>
  <?php $attributes = array(
    'id'      => 'login_form',
    'class'   => 'form-horizontal', 
    'style'   => 'width: 300px; margin: 0 auto;'
    );?>
<?php echo form_open('Users/login',$attributes); ?>
<p>
  <?php echo form_label('Username:');?>
  <?php
   $data  = array(
    'name'        => 'username', 
    'placeholder' => 'Enter Username', 
    'style'       =>'width:90%', 
    'value'       => set_value('username'),
    'class' => 'form-control'
    );
   ?>
   <?php echo form_input($data); ?>
</p>
<p>
  <?php echo form_label('Password:');?>
  <?php
   $data  = array(
    'name'        => 'password', 
    'placeholder' => 'Enter Password', 
    'style'       => 'width:90%', 
    'value'       => set_value('password'),
    'class'       => 'form-control'
    );
   ?>
   <?php echo form_password($data); ?>
</p>

<p>

  <?php
   $data    = array(
   'name'   => 'submit',
   'class'  => 'btn btn-primary', 
   'value'  => 'login');
   ?>
   <?php echo form_submit($data); ?>
</p>
<p>Not registered? <a href="<?php echo base_url('Signup'); ?>">Sign Up</a>
</p>
<?php echo form_close(); ?>
</div>

The html form pattern displayed here are from the codeigniter form helper class, this ensures security of the form data sent to the databse, for now let’s focuss on the flow from the controller to the view as I’ve explained in the home view.

4. Signup.php

This has the flow and structure of the login form

<div class="well" style="width:304px;text-align: center">
    <?php if($this->session->flashdata('user_signup_error')) : ?>
  <p class="alert alert-dismissable alert-success text-center"><?php echo $this->session->flashdata('user_signup_error');?></p>
<?php endif; ?>
<?php if($this->session->flashdata('user_exist')) : ?>
  <p class="alert alert-dismissable alert-danger text-center"><?php echo $this->session->flashdata('user_exist');?></p>
<?php endif; ?>
<h1>Sign Up</h1>
<p>Please fill out the form below to create an account</p>
(html comment removed: Display Errors)
(html comment removed: Display Errors)
<?php if($this->session->flashdata('image_error')) : ?>
  <p class="alert alert-dismissable alert-danger text-center"><?php echo $this->session->flashdata('image_error');?>
  </p>
<?php endif; ?>
<?php echo validation_errors('<p class="alert alert-dismissable alert-danger">'); ?>
<?php $attributes = array('id' => 'login_form','class'=> 'form-horizontal','enctype'=>'multipart/form-data','role'=>'form');?>
<?php echo form_open('Users/createUser',$attributes); ?>

(html comment removed: field: Username)
<p>
    <?php echo form_label('Username:'); ?>
    <?php
    $data = array(
        'name'  => 'username',
        'value' => set_value('username'),
        'class' => 'form-control'
        );

        ?>
        <?php echo form_input($data); ?>
</p>

(html comment removed: field: Password)
<p>
    <?php echo form_label('Password:'); ?>
    <?php
    $data = array(
        'name'  => 'password',
        'value' => set_value('password'),
        'class' => 'form-control'
        );

        ?>
        <?php echo form_password($data); ?>
</p>

(html comment removed: field: Confirm Password)
<p>
    <?php echo form_label('Confirm Password:'); ?>
    <?php
    $data = array(
        'name'  => 'password2',
        'value' => set_value('password'),
        'class' => 'form-control'
        );

        ?>
        <?php echo form_password($data); ?>
</p>
(html comment removed: field: Submit Buttons)
<p>
    <?php
    $data = array(
        'name'  => 'submit',
        'value' => 'Sign Up',
        'class' => 'btn btn-primary'
        );

        ?>
        <?php echo form_submit($data); ?>
</p>
<p>Already registered? <a href="<?php echo base_url('Login'); ?>">Login</a>
</p>

<?php echo form_close(); ?>
</div>

Models

1. User_model:

It has the two methods** login_user** and create_user
I will include comments in the code, we have called these two methods in the Users controller, the result that is obtained from here is what the controller will give to the views either a valid data with success message or error message.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 /**
 * 
 */
 class User_model extends CI_Model
 {
    // student login function
    public function login_user($username,$password){ //arguments passed from the controller
        $enc_password = md5($password); //encrypt the password so it will match with the user's password in the database
        //where clause
        $this->db->where('username',$username);// codeigniter database helper function for where clause
        $this->db->where('password',$enc_password);// codeigniter database helper function for where clause
        $result = $this->db->get('users'); //codeigniter database helper function equivalent to select from clause
        if($result->num_rows() == 1){
            return true;// return true if the user is already in the database
        } else {
            return false;
        }
    }

    public function create_user($data)//user data sent from the controller to be inserted by the odel method
    {
        $insert = $this->db->insert('users',$data); //ci helper function to insert the data passed from the controller into the database
        return $insert; //this will return true if the data was inserted 
    
    }

 }

?>

2. Authentication model:

It validates the user and reports to the controller before the controller even contacts the model to create the user.

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Authentication_model extends CI_Model {

    function validate_user($postData){//argument passed from the controller for data processing
        //save the posted data sent from the ccontroller into variables to avoid taking direct post values.
       $username = $postData['username'];
       $password = md5($postData['password']); // encrypt the password to match with the emcrypted one in the database
        $this->db->select('*');//ci database helper for select * query
        $this->db->where('username',  $username);//check if the username posted by the user is same as that in the database
        $this->db->where('password', $password);//check if the password posted by the user is same as that in the database
        $this->db->from('users');
        $query=$this->db->get();
        if ($query->num_rows() == 0)
            return false;
        else
            return $query->result();
    }

}

At this point your models folder should now look like this.
models.jpg

This has been quite long but if you’ve followed and understood up to this point then the MVC pattern should be quite clear to you.

I’ve not emphasized more on the design aspect simply because our focus here is mainly to understand how the MVC pattern works in codeigniter, but not withstanding, I will add the assets folder in the project. The assets folder is were all your images, css, js plugins and other external files will be, it is usually placed in the root directory of the application . once this is added, then your application directory will now look like this.
assets.jpg

This brings us to the end of this section of the tutorial series, feel free to ask were you are not clear enough, I will also share a link to my git hub repository for the full code where you can download and study as well.

Curriculum

CodeIgniter Part 1: Initial Setup

References

https://www.codeigniter.com/userguide3/

Git hub repository for this project

Sort:  

Thank you for your contribution to the open source community. It is appreciated.

I have several important ideas which could significantly affect the quality of the contribution, especially in the presentation part.

  • Always remember teaching goal: While I was reading your contribution, there were times that the flow of the tutorial was heading somewhere but not the main goal.
  • Approach like it's a book: Since both of them are to teach, prepare and outline your tutorial like it is a book. Write/draw a solid structure of the content, and stay loyal to the outline. And I would encourage you to provide it below the "What will I learn?" section since it does provide more information about the content.
  • Avoid too long code blocks: Constantly facing long code blocks cause readers to feel lost on the page, especially when they need to check the explanation. One of the ways to deal with this problem is providing screenshots of the code in a pretty format. This is also preferable considering that the STEEM front-end platforms don't provide a good code formatting option.
  • Avoid too dense content: You don't have to push all the information in just a tutorial. If you think that the reader should have a greater background to understand the rest, provide external resources or separate your content into multiple tutorials. External references always increase the quality and serve multiple options to the reader.

I hope my thoughts inspire you to improve your future tutorials. I really love to see you put effort to prepare your contributions.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

This is wonderful, thanks for the much effort in making a full review of tutorial, i will try my very best to correct these in my next post on the series

Hey @roj
Here's a tip for your valuable feedback! @Utopian-io loves and incentivises informative comments.

Contributing on Utopian
Learn how to contribute on our website.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

I liked the content of your tutorial.

  • It's easy to understand
  • Your diagram is eye catchy, nice color
  • Most of the code is explained

However, I have some few advice for this tutorials to make it readable:

  • zoom the screenshotted code
  • for long code, try to break it down
  • avoid starting code with long space or tab like:
                     CREATE TABLE `users` (
                     `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
                     `username` varchar(255) NOT NULL,
                     `password` varchar(255) NOT NULL
                   ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Hey @drsensor
Here's a tip for your valuable feedback! @Utopian-io loves and incentivises informative comments.

Contributing on Utopian
Learn how to contribute on our website.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

thanks a lot for your obsrvervation. It's well noted. I will surely correct these in the upcoming post

Congratulations @mrobele!
Your post was mentioned in the Steemit Hit Parade for newcomers in the following category:

  • Pending payout - Ranked 4 with $ 83

I also upvoted your post to increase its reward
If you like my work to promote newcomers and give them more visibility on Steemit, feel free to vote for my witness! You can do it here or use SteemConnect

Hey @mrobele
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Nice and educative piece of information. I have learnt something new today.
The tutorial is well written and well delivered. I like the pictorial view giving make the codes come to life.

Very easy to understand and follow for a newbie developer like me. Thumbs up. Waiting for the next part.

Thanks a lot. Stay tuned for the next on the series

Get your post resteemed over 90000+ followers and get upto $21+ SBD value Upvote.
Your post will skyrocket and give you maximum exposer.

<< EXCLUSIVE OFFER >>

WE are giving 20 UPVOTS WORTH 1 SBD AND 10 FOLLOWERS.

Click HERE FOR GET THE OFFER