Saturday, January 15, 2011

Codeigniter full MVC User Registration example

1. create the following view vie files in the application/views directory of the codeigniter framework.


(1). index.php 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page</title>
</head>

<body>
<?php
$this->load->helper('url');
$this->load->model("UserService");

$userService=new UserService();

$userIDs=$userService->getAllRegisteredUsersIDs();

?>
<table>
<tr><td>username</td><td>Edit</td><td>Remove</td></tr>
<?php for($index=0;$index<sizeof($userIDs);$index++){ ?>
<tr>
<td>Username</td><td><a href="<?php echo base_url(); ?>userAdministration/editUserDetails/<?php echo $userIDs[$index]; ?>">Edit User </a></td>
<td><a href="<?php echo base_url(); ?>userAdministration/removeRegisteredUser/<?php echo $userIDs[$index]; ?>">Remove User </a></td>
</tr>
<?php
}
?>

<tr><td><a href="<?php echo base_url(); ?>userAdministration/register">Add New User </a></td></tr>
</table>
</body>
</html> 

2. userRegisterView.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

.error_color{
color:#FF0000;
}
</style>
<script type="text/javascript">

function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername



function passwordValidation(passwordConf){

var password=(document.getElementById("password")).value;



if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }

var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","http://localhost/mvc/index.php/userAdministration/ajaxValidation",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);


}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page- Chathuranga Tennakoon</title>
</head>
<body>
<?php
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');


$this->form_validation->set_error_delimiters('<div class="error_color">', '</div>');

echo form_open(base_url().'userAdministration/register',array('method'=>'post','class'=>'registration_form_div'));
?>
<table>
  <tr>
    <td><label>Username </label>
    </td>
    <td><input type="text"  id="username" name="username" value="<?php echo set_value('username'); ?>" onchange="validateForm('username',this.value,'txtUsername')" />
    </td>
    <td><p><span id="txtUsername"> <?php echo form_error('username'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>First Name </label></td>
    <td><input type="text" id="firstName" name="firstName" value="<?php echo set_value('firstName'); ?>" onchange="validateForm('firstName',this.value,'txtFirstName')"/>
    </td>
    <td><p><span id="txtFirstName"> <?php echo form_error('firstName'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Last Name </label></td>
    <td><input type="text"  id="lastName" name="lastName" value="<?php echo set_value('lastName'); ?>" onchange="validateForm('lastName',this.value,'txtLastName')"/>
    </td>
    <td><p><span id="txtLastName"> <?php echo form_error('lastName'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Password </label></td>
    <td><input id="password" type="password" name="password" value="<?php echo set_value('password'); ?>" />
    </td>
    <td><p><span id="txtPassword"><?php echo form_error('password'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>password confirmation </label></td>
    <td><input type="password" id="passwordConfirmation" name="passwordConfirmation" value="<?php echo set_value('passwordConfirmation'); ?>" onchange="passwordValidation(this.value)"/>
    </td>
    <td><p><span id="txtPasswordConf"><?php echo form_error('passwordConfirmation'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Age </label></td>
    <td><input type="text" name="age" value="<?php echo set_value('age'); ?>" onchange="validateForm('age',this.value,'txtAge')"/>
    </td>
    <td><p><span id="txtAge"> <?php echo form_error('age'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Address </label></td>
    <td><input type="text" name="address" value="<?php echo set_value('address'); ?>" onchange="validateForm('address',this.value,'txtAddress')"/>
    </td>
    <td><p><span id="txtAddress"><?php echo form_error('address'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Email </label></td>
    <td><input type="text" name="email" value="<?php echo set_value('email'); ?>" onchange="validateForm('email',this.value,'txtEmail')"/>
    </td>
    <td><p><span id="txtEmail"><?php echo form_error('email'); ?></span></p></td>
  </tr>
  <tr>
    <td><label>Telephone </label></td>
    <td><input type="text" name="telephone" value="<?php echo set_value('telephone'); ?>" onchange="validateForm('telephone',this.value,'txtTelephone')" />
    </td>
    <td><p><span id="txtTelephone"><?php echo form_error('telephone'); ?> </span></p></td>
  </tr>
</table>
<input type="submit" value="Register" name="registerUser" class="registration_textfield" />
<?php
echo  form_close(); 
?>
</body>
</html>

3. userEditView.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

.error_color{
color:#FF0000;
}
</style>
<script type="text/javascript">

function createXmlHttpObject(){
  var xmlhttp="";
  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  return xmlhttp;
}  


function sendAjaxHttpRequest(xmlhttp,url,parameterName,parameterValue){

var parameters=parameterName+"="+parameterValue+"&isAjax=true";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);

}


function validateForm(elementName,elementValue,SpanTagId)
{

if (elementValue.length==0)
  {
  document.getElementById(SpanTagId).innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(SpanTagId).innerHTML=xmlhttp.responseText;
    }
  }

sendAjaxHttpRequest(xmlhttp,"http://localhost/mvc/index.php/userAdministration/ajaxValidation",elementName,elementValue,SpanTagId);

}//validateUsername



function passwordValidation(passwordConf){

var password=(document.getElementById("password")).value;



if (passwordConf.length==0)
  {
  document.getElementById("txtPasswordConf").innerHTML="";
  return;
  }

xmlhttp=createXmlHttpObject();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtPasswordConf").innerHTML=xmlhttp.responseText;
    }
  }

var parameters="password="+password+"&passwordConf="+passwordConf+"&isAjax=true";
xmlhttp.open("POST","http://localhost/mvc/index.php/userAdministration/ajaxValidation",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);


}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Home Page- Chathuranga Tennakoon</title>
</head>
<body>
<?php
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');

$this->form_validation->set_error_delimiters('<div class="error_color">', '</div>');

echo form_open(base_url().'userAdministration/editUser',array('method'=>'post','class'=>'registration_form_div'));
?>
<table>
  <tr>
    <td><label>Username </label></td>
    <td><input type="text" name="username" value="<?php if(isset($username)){ echo $username; }else{ echo set_value('username'); } ?>" onchange="validateForm('username',this.value,'txtUsername')" />
      <input type="hidden" value="<?php echo $userID; ?>" name="userID" id="userID" />
    </td>
    <td><p><span id="txtUsername"> <?php echo form_error('username'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>First Name </label></td>
    <td><input type="text" name="firstName" value="<?php if(isset($firstName)){ echo $firstName; }else{ echo set_value('firstName'); } ?>" onchange="validateForm('firstName',this.value,'txtFirstName')" />
    </td>
    <td><p><span id="txtFirstName"> <?php echo form_error('firstName'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Last Name </label></td>
    <td><input type="text" name="lastName" value="<?php if(isset($lastName)){ echo $lastName; }else{ echo set_value('lastName'); } ?>" onchange="validateForm('lastName',this.value,'txtLastName')"  />
    </td>
    <td><p><span id="txtLastName"> <?php echo form_error('lastName'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Password </label></td>
    <td><input type="password" name="password" value="<?php if(isset($password)){ echo $password; }else{ echo set_value('password'); } ?>"/>
    </td>
    <td><?php echo form_error('password'); ?> </td>
  </tr>
  
  <tr>
    <td><label>password confirmation </label></td>
    <td><input type="password" name="passwordConfirmation" value="<?php if(isset($password)){ echo $password; }else{ echo set_value('passwordConfirmation'); } ?>" onchange="passwordValidation(this.value)" />
    </td>
    <td><p><span id="txtPasswordConf"> <?php echo form_error('passwordConfirmation'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Age </label></td>
    <td><input type="text" name="age" value="<?php if(isset($age)){ echo $age; }else{ echo set_value('age'); } ?>" onchange="validateForm('age',this.value,'txtAge')" />
    </td>
    <td><p><span id="txtAge"> <?php echo form_error('age'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Address </label></td>
    <td><input type="text" name="address" value="<?php if(isset($address)){ echo $address; }else{ echo set_value('address'); } ?>" onchange="validateForm('address',this.value,'txtAddress')" />
    </td>
    <td><p><span id="txtAddress"> <?php echo form_error('address'); ?> </span></p></td>
  </tr>
  <tr>
    <td><label>Email </label></td>
    <td><input type="text" name="email" value="<?php if(isset($email)){ echo $email; }else{ echo set_value('email'); } ?>" onchange="validateForm('email',this.value,'txtEmail')" />
    </td>
    <td><p><span id="txtEmail"> <?php echo form_error('email'); ?> </span></p></td>
  </tr>
  
  <tr>
    <td><label>Telephone </label></td>
    <td><input type="text" name="telephone" value="<?php if(isset($telephone)){ echo $telephone; }else{ echo set_value('telephone'); } ?>" onchange="validateForm('telephone',this.value,'txtTelephone')" />
    </td>
    <td><p><span id="txtTelephone"> <?php echo form_error('telephone'); ?> </span></p></td>
  </tr>
  
</table>
<input type="submit" value="Register" name="registerUser" class="registration_textfield" />
<?php
echo  form_close(); 
?>
</body>
</html>

2. Models

(1) UserModel.php
<?php
class UserModel extends CI_Model {

     var $userID='';
     var $username = '';
     var $password = '';
     var $email = '';
     var $firstName = '';
     var $address = '';
     var $age = '';
     var $telephone = '';
    

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    
    function setUserID($userIDprovided){
    
        $this->userID=$userIDprovided;
    }
    
    function getUserID(){
    
    return $this->userID;
    }
    
    function getUserName(){
    
    return $this->username;
    }
    
    function setUserName($usernameProvided){
    
    $this->username=$usernameProvided;
    
    }
    
    
    function getFirstName(){
    
    return $this->firstName;
    }
    
    function setFirstName($fisrtNameProvided){
    
    $this->firstName=$fisrtNameProvided;
    
    }
    
    
    function getLastName(){
    
    return $this->lastName;
    }
            
    function setLastName($lastNameProvided){
    
     $this->lastName=$lastNameProvided;
    
    }
    
    
    function getEmail(){
    
    return $this->email;
    }
    
    function setEmail($emailProvided){
    
    $this->email=$emailProvided;
    
    }    
    
    
    function getAge(){
    
    return $this->age;
    }
    
    function setAge($ageProvided){
    
    $this->age=$ageProvided;
    
    }
    
    
    function getTelephone(){
    
    return $this->telephone;
    }
    
    function setTelephone($telephoneProvided){
    
    $this->telephone=$telephoneProvided;
    
    }
    
    
    function getAddress(){
    
    return $this->address;
    }
    
    function setAddress($addressProvided){
    
    $this->address=$addressProvided;
    
    }
    

    function getPassword(){
    
    return $this->password;
    }
    
    function setPassword($passwordProvided){
    
    $this->password=$passwordProvided;
    
    }
    
    
        
}//class
        
?>    
  

(2.) EmailClass.php
<?php
class EmailClass extends CI_Model {

     var $emailUsername="xxxxxxxt@gmail.com";
     var $emailPassword="yourPassword";
     var $emailHost="ssl://smtp.googlemail.com";
     var $emailProtocol="smtp";
     var $emailPort="465";
     var $emaiType="html";
    
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        //$this->load->helper("url");
    }
    
    
function sendEmail($emailFrom,$emailTo,$subject,$message){
    
 $config = Array(
  'protocol' => $this->emailProtocol,
  'smtp_host' => $this->emailHost,
  'smtp_port' => $this->emailPort,
  'smtp_user' => $this->emailUsername, // change it to yours
  'smtp_pass' => $this->emailPassword, // change it to yours
  'mailtype' => $this->emaiType,
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);
  $this->load->library('email', $config);
  $this->email->set_newline("\r\n");
  $this->email->from($emailFrom); // change it to yours
  $this->email->to($emailTo); // change it to yours
  $this->email->subject($subject);
  $this->email->message($message);

  if($this->email->send())
  {

   return true;

  }
  else
  {
   show_error($this->email->print_debugger());
   
   return false;
  }
  
    
}
    
        
}//class
        
?>    


(3.)UserService.php
<?php
class UserService extends CI_Model {


   function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        $this->load->database();    

    }
    
    
     function createNewUser($user){
        
            
      $username=$user->getUserName();
      $firstName=$user->getFirstName();
      $lastName=$user->getLastName();
      $email=$user->getEmail();
      $telephone=$user->getTelephone();
      $age=$user->getAge();
      $password=$user->getPassword();
      $address=$user->getAddress();

      
       $insertStatus=$this->db->insert('user',array('username'=>$username ,'firstName'=>$firstName ,'lastName'=>$lastName ,'email'=>$email ,'age'=>$age ,'password'=>$password ,'address'=>$address      ,'telephone'=>$telephone)); 
       
       if($insertStatus){
       
       return true;
       }
       else{
       
       return false;
       
       }
    
    }//createNewUser
    
    
    
    
    function editUserDetails($user){
    
    
      $username=$user->getUserName();
      $firstName=$user->getFirstName();
      $lastName=$user->getLastName();
      $email=$user->getEmail();
      $telephone=$user->getTelephone();
      $age=$user->getAge();
      $password=$user->getPassword();
      $address=$user->getAddress();

        $this->db->where('userID', $user->getUserID());
       $updatedStatus=$this->db->update('user',array('username'=>$username ,'firstName'=>$firstName ,'lastName'=>$lastName ,'email'=>$email ,'age'=>$age ,'password'=>$password ,'address'=>$address,'telephone'=>$telephone)); 
       
       if($updatedStatus){
       
       return true;
       }
       else{
       
       return false;
       
       }
    
    
    
    
    }//editUserDetails
    
    
    
    
    function getAllRegisteredUsersIDs(){
        
    $this->db->select('userID');
    $query = $this->db->get('user');
    $selectedDataArray=array();
    
    $i=0;
    
    foreach ($query->result() as $row){
    
    $selectedDataArray[$i]=$row->userID;
    $i++;
    }
    
     return $selectedDataArray;
    
    }//getAllRegisteredUsersIDs
    
    
    
    
    
    function removeRegisteredUser($user){
        
    $this->db->where('userID', $user->getUserID());
    $this->db->delete('user'); 
    
    }//removeRegisteredUser
    
    
    
    
    function getSelectedUserDetails($user){
        
        $query = $this->db->get_where('user', array('userID' => $user->getUserID()));
    
        $selectedData="";
        
        foreach ($query->result() as $row){

         $selectedData=array("username"=>$row->username,"firstName"=>$row->firstName,"lastName"=>$row->lastName,"password"=>$row->password,"age"=>$row->age,"telephone"=>$row->telephone,"address"=>$row->address,"email"=>$row->email,"userID"=>$row->userID);
        
        }
        
        return $selectedData;
        
    }//getSelectedUserDetails
    
    
    
    function isUserNamealreadyRegisterd($user){
        
    $username=$user->getUserName();
    
    $query = $this->db->get_where('user', array('username' => $username));
    
    if($query->num_rows()==0){
    
    return false;
    
    }
    else{
    
    return  true;
    }
      
    }//function
    
    
   }//class
    
    
    
?>
 
3.  Controller

UserAdministration.php
<?php

class userAdministration extends CI_Controller {


    public function index()
    {
        echo 'welcome to userAdministration Controller';
    }
    
    
    public function register(){
    
        //echo "registering new user";
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim');
        $this->form_validation->set_rules('passwordConfirmation', 'Password Confirmation', 'required|matches[password]|xss_clean|trim');
        $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');
        $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');



        if ($this->form_validation->run() == FALSE){
        
            $this->load->view('userRegisterView');
        
        }
        else
        {
             //loading the required model and service classes
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->model("EmailClass");

            
            $userModel=new UserModel();    
            $userService=new UserService();
            
            $userModel->setUserName($this->input->post('username', TRUE));
            $userModel->setFirstName($this->input->post('firstName', TRUE));
            $userModel->setLastName($this->input->post('lastName', TRUE));
            $userModel->setPassword($this->input->post('password', TRUE));
            $userModel->setAge($this->input->post('age', TRUE));
            $userModel->setAddress($this->input->post('address', TRUE));
            $userModel->setTelephone($this->input->post('telephone', TRUE));
            $userModel->setEmail($this->input->post('email', TRUE));
                                                
            $dbInserted=$userService->createNewUser($userModel);

            
            if($dbInserted){
            
                //echo "registration email should be sent";
        
              $emailClass=new EmailClass();
            
              $emailSentStatus=$emailClass->sendEmail("chathuranga.t@gmail.com","chathuranga.t@gmail.com","new user registration","chathurangat.blogspot.com");
            
             if($emailSentStatus){
            
             redirect(base_url()); //with success message
            
             }
             else{
            
             redirect(base_url()); //with error message
             }    
            
            }//if
                                    
        }//else            
    }//register    
    
    
    function removeRegisteredUser($userID){
    
    
    //echo "request for remeving user with  userID ".$userID;
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->helper("url");

            $userModel=new UserModel();    
            $userService=new UserService();
      
            $userModel->setUserID($userID);
            
            $userService->removeRegisteredUser($userModel);
            
            redirect(base_url()); //with error message
            
         
    }//removeRegisteredUser
    
    
    
    function editUserDetails($userID){
    
    //echo "request for editing user with userID ".$userID;
    
             $this->load->helper(array('form', 'url'));
             $this->load->library('form_validation');        
             $this->load->model("UserModel");
             $this->load->model("UserService");
             $this->load->helper("url");

            $userModel=new UserModel();    
            $userService=new UserService();
      
            $userModel->setUserID($userID);
            
            $retievedUserData=$userService->getSelectedUserDetails($userModel);
            
            $this->load->view("userEditView",$retievedUserData);
            
    
    }//display Edit user details from
    
    
    
    
    public function editUser(){
    
        //echo "registering new user";
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|xss_clean|trim');
        $this->form_validation->set_rules('passwordConfirmation', 'Password Confirmation', 'required|matches[password]|xss_clean|trim');
        $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');
        $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');



        if ($this->form_validation->run() == FALSE){
        
            $this->load->view('userRegisterView');
        
        }
        else
        {
             //loading the required model and service classes
             $this->load->model("UserModel");
             $this->load->model("UserService");

            
            $userModel=new UserModel();    
            $userService=new UserService();
            
            $userModel->setUserName($this->input->post('username', TRUE));
            $userModel->setFirstName($this->input->post('firstName', TRUE));
            $userModel->setLastName($this->input->post('lastName', TRUE));
            $userModel->setPassword($this->input->post('password', TRUE));
            $userModel->setAge($this->input->post('age', TRUE));
            $userModel->setAddress($this->input->post('address', TRUE));
            $userModel->setTelephone($this->input->post('telephone', TRUE));
            $userModel->setEmail($this->input->post('email', TRUE));
            $userModel->setUserID($this->input->post('userID', TRUE));    
                                            
            $dbCommited=$userService->editUserDetails($userModel);
            
            
            if($dbCommited){
            
             redirect(base_url()); //with success message
            
             }
             else{
            
             redirect(base_url()); //with error message
             }    
            
                                    
        }//else            
    }//editUser    
    
    
    
    function ajaxValidation(){
    
    $this->load->model("UserModel");
    $this->load->model("UserService");

      $userModel=new UserModel();    
      $userService=new UserService();
    //validating user input using ajax
    
     $this->load->helper(array('form', 'url'));
     $this->load->library('form_validation');
    
    $username=$this->input->post('username');
    $email=$this->input->post('email');
    $address=$this->input->post('address');
    $telephone=$this->input->post('telephone');
    $age=$this->input->post('age');
    $lastName=$this->input->post('lastName');
    $firstName=$this->input->post('firstName');
    $password=$this->input->post('password');    
    $passwordConf=$this->input->post('passwordConf');        
        
    //username validate                
    if(isset($username) && $username!=""){
    
    $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|xss_clean|trim|alpha');

    if($this->form_validation->run() == FALSE){
    
    echo validation_errors();
    
    }
    else{
    
    $userService=new UserService();
    $userModel=new UserModel();
    
    $userModel->setUserName($username);
    
    $userStatus=$userService->isUserNamealreadyRegisterd($userModel);
    
    if($userStatus){
    
    echo "Username is already taken";
    
    }
    else{
    
    echo "Username is avaialable";
    
    }
    }
    }//username
    
    
    
    //validating email
    
    if(isset($email) && $email!="" ){
    
     $this->form_validation->set_rules('email', 'Email', 'required|valid_email|xss_clean|trim');

    if($this->form_validation->run() == FALSE){
    
    echo validation_errors();
    
    }
    
    }//email
    
    
      //validating address
    
        if(isset($address) && $address!="" ){
    
        $this->form_validation->set_rules('address', 'Address', 'required|xss_clean|trim');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
       }

       }//address
    
    
    
        
    
       //validating age
    
       if(isset($age) && $age!="" ){
    
         $this->form_validation->set_rules('age', 'Age', 'required|xss_clean|trim|integer');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
         }
                 
        }//age
    
    
        //validating telephone
    
        if(isset($telephone) && $telephone!="" ){
    
        $this->form_validation->set_rules('telephone', 'Telephone', 'required|xss_clean|trim|exact_length[10]|integer');

        if($this->form_validation->run() == FALSE){
    
        echo validation_errors();
    
         }
                 
        }//telephone
    
    
       //validating first name
    
        if(isset($firstName) && $firstName!="" ){
    
          $this->form_validation->set_rules('firstName', 'First Name', 'required|xss_clean|trim|alpha');

        if($this->form_validation->run() == FALSE){
    
          echo validation_errors();
    
         }
                 
        }//firstName
    
    
    
        //validating last name
    
        if(isset($lastName) && $lastName!="" ){
    
        $this->form_validation->set_rules('lastName', 'Last Name', 'required|xss_clean|trim|alpha');

        if($this->form_validation->run() == FALSE){
    
         echo validation_errors();
    
         }
                 
        }//lastName
        
        
        
        
        if(isset($password) && $password!="" && isset($passwordConf) && $passwordConf!="" ){
        
    
        if($password!=$passwordConf){
        
        echo  "Password and Password Confirmation field does not match";
                
        }

        }//password
    
    
    
    }//ajaxValidation
    
}//class

?> 




Configuration in application/config/database.php
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'test_mvc';
$db['default']['dbdriver'] = 'mysql';


My SQL Table Structure
CREATE TABLE IF NOT EXISTS `user` (
  `userID` int(11) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `firstName` varchar(100) NOT NULL,
  `lastName` varchar(100) NOT NULL,
  `address` varchar(500) NOT NULL,
  `email` varchar(100) NOT NULL,
  `age` int(11) NOT NULL,
  `telephone` varchar(100) NOT NULL,
  PRIMARY KEY  (`userID`),
  UNIQUE KEY `username` (`username`)
) 





regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hello Admin this is for you...
    Submit excerpts of your blog and gain better credibility and high traffic to your website.Let people know who you are, what you think and what you do. Get access to the world. 21Articles
    I am not a spammer...

    ReplyDelete
  3. please describe how to execute this

    ReplyDelete
  4. Nice Tutorial....I got useful information from this tutorial...Here is also a way to find Simple registration form using codeigniter

    ReplyDelete
  5. thanks mr.D.arunkumar

    ReplyDelete