Learn how to code in Codeigniter - The php framework - part 2

In the first tutorial, we learned how to install Codeigniter. Now we are going to create a form which submits data to the server and saves it to MySQL database. Codeigniter has the predefined functions to do its job.  Codeigniter comes with various libraries and helpers. We will also teach you how to use a helper in this tutorial. Helpers:-Helpers file are the file which contains a function to help you to create your web application/website in a particular category. e.g. file helper helps to deal with file handling, form helper can help in creating form element and URL helpers can create URLs. You can create your own helper file or extend the existing one.

We are going to create a form which sends data to the server via post method with the help of form helper. Thier is two way of enabling any helper one is in autoload.php which is global or another method is you can enable it in your controller.

First method:-Go to C:/xampp/yourproject/application/config/autoload.php  and set $autoload['helper'] = array(); to $autoload['helper']=array('form','text',......);

$autoload['helper'] = array('form','text','url');

Now how to code in Codeigniter:- we have to deal with three files in order to work in Codeigniter one file in view, one in the model and one in the controller.

1. Create file name  signup.php in view folder .create a file name signup.php in controller folder and signup_model.php in model folder of the application directory.

note: the controller file is the file which handles view and model both.

create database

1. create database named example in your mysql phpmyadmin and create a table name tbl_users.


CREATE TABLE `tbl_users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `activation_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
, PRIMARY KEY (`user_id`));

. Now we have to configure database.php file in application/config directory.

3. Now open application/view/signup.php in your text editor and create a form. In addition, we are using Bootstrap 4, We have to include bootstrap CSS file in the header section and the js file in the footer section of the document.


<?php if(isset($msg)){echo $msg;}?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="<?php echo base_url('assets/bootstrap/bootstrap.min.css');?>" rel="stylesheet">
<title>
Login Example</title>
</head>
<body>
<div class="card mt-3">
<div class="card-body">
<div class="row justify-content-center">
<div class="col-12 col-sm-6 col-md-6 col-lg-6 col-xl-6">
<div class="card mx-5 my-5">
<div class="card-body bg-secondary text-white font-weight-bold">
<form autocomplete="off" action="<?php echo base_url('Signup/signup');?>" method="post" >
<div class="form-group" >
<label for="username">
User Name</label>
<input type="text" class="form-control" id="username" aria-describedby="userlHelp" autocomplete="off">
<small id="userHelp" class="form-text text-dark">
Please enter user name.</small>
</div>
<div class="form-group">
<label for="password">
Password</label>
<input type="password" class="form-control" id="password" autocomplete="off">
<small id="passHelp" class="form-text text-dark">
Please enter password.</small>
</div>
<button type="submit" id="login" class="d-inline btn btn-success">
Login</button>
<a href="<?php echo base_url();?>signup" class="d-inline btn btn-success">
Sign Up</a>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url('js/jquery.min.js');?>">
</script>
<script type="text/javascript" src="<?php echo base_url('assets/bootstrap/js/popper.js');?>">
</script>
<script type="text/javascript" src="<?php echo base_url('assets/bootstrapjs//bootstrap.min.js');?>">
</script>
<script type="text/javascript" src="<?php echo base_url('js/jquery.toaster.js');?>">
</script>
</body>
</html>

Now we have to create a model file Signup_model.php in application/models/ folder. Models are the classes which deal with data and its transactions to controllers.


<?php
class Signup_model extends CI_Model
{
  function __construct()
  {
  	parent::__construct();
  	$this--->load->database();
  }
  public function check_login($username,$password)
  {
  $this->db->select("*");
  $this->db->where("username",$username);
  $this->db->password("password",$password);
  $res=$this->db->get("tbl_users");
  if($res->num_rows()>0)
  {
  return true;
  }
  else
  {
  return false;
  }
  }
  public function signup($username,$password)
  {
  if($this->check_login($username,$password)===false)
  {
  $data=array("username"=>$username,"password"=>$password);
       if($this->db->insert("tbl_users",$data))
       {
       	return TRUE;
       }
       else
       {
       	return FALSE;
       }
  }
  else
  {
  return false;
  }
       
  }
}
?>

Now we have to create a controller class in the application/controllers folder of your project.file name will be signup.php.


<?php
class Signup extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
	}
	public function signup()
	{
		$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');

        if ($this->form_validation->run() == FALSE)
                {
                        $this->load->view("signup");
                }
                else
                {
                    $this->load->model("Signup_model");
    if($this->Signup_model->signup($this->input->post("username"),$this->input->post("password")))
                    {
                      $data["msg"]="Your data is saved successfully";  
                    }
                    else
                    {
                    $data["msg"]="Something went wrong!";
                    }
                	 
                       $this->load->view("signup",$data); 
                }
	}
}
?>

now go to your browser URL bar and type localhost/yourprojectname/Signup/signup. It will show the form which we have created in above. you can fil the form and when you submit it  will display a data saved successfully message. You can also use validation before it submits data to the database. You have to enable validation library on your application/config/autoload.php file or you can enable validation in your controller definition.

$autoload['libraries'] = array('form_validation');

or


public function signup()
	{
		$this->load->library('form_validation');
        .......
        .......
        .......
}

Form validation library will validate the input according to your given rule in your controller file. Codeigniter set_rules function of the form_validation library is used for this purpose. example:-


$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');

1. The first parameter is the name of the name selector of your HTML input element .select parameter is the user-defined name of that input field, and the third parameter will be the rules to filter the value of the input.

That's it you are all done. Thank you..

                                 Ok, I was kidding, don't feel what the heck. I  am going to explain it.

When it comes to CodeIgniter, you have to follow some rules and convention.

Rule 1:- Every class of controller or model has to be extended to its base class. i.e. for controller CI_Controller and for model class CI_Model.

example:-


<?php
/*--------a controllers definition---------*/
class signup extends CI_Controller
{
................
................
................
}


/*--------a Model class definition---------*/
class Signup_model extends CI_Model
{
................
................
................
}
?>

Convention:- when you are going to create a constructor function for child class then you also initialize base class constructor their.


class Signup_model extends CI_Model
{
  function __construct()
  {
  	parent::__construct();
  	$this->load->database();
    ...........
    ...........
    ...........
  }
}

Now i am going to tell you how codeigniter works.

When you type http://localhost/yourproject/Signup/signup in your browser it routes to signup function of Signup class of CI controller. signup function checks whether form validation function ran or not. if validation function does not run than it displays the login.php view or if validation function runs than it calls model Singup_model, signup function of CI model saves the signup data to the server if user not exists in the database and returns true. if the user does exist or something went wrong it returns boolean false. If the CI model signup function returns true then ci controller function sends "data saved successfully " message to signup view file else it sends "error " or "something went wrong" message to signup view.

Other posts