Welcome Guest, Not a member yet? Register   Sign In
question: how to pass a variable from model to view
#1

[eluser]johansonevR[/eluser]
hi there,
I have a function inside a 'model'
Code:
function register($name){
    $query=$this->db->query("Select * from users where name='".$name."' ;");
        if($query->num_rows()>0){
            $error['name']="User with that Name exists";
            }
}
I want to send this error to the 'view' so i can design it.
I can call the function from the 'controller'
Code:
$this->my_model->register($name);
but what do i do to access the $error variable?
#2

[eluser]Ben Edmunds[/eluser]
You could do something like this:

Code:
MODEL

function register($name){
    $query=$this->db->query("Select * from users where name='".$name."' ;");
    if($query->num_rows()>0){
        return "User with that Name exists";
    }
    return TRUE;
}


CONTROLLER

$result = $this->user_model->register($name);
if ($result == TRUE) {
  echo 'all good';
}
else {
  echo $result;
}

or you could return an array with the error/success message. Or create a getter and setter for the errors.

Many options...
#3

[eluser]johansonevR[/eluser]
tnx
#4

[eluser]Ben Edmunds[/eluser]
If you do it the way I posted you might want to use === TRUE instead of just ==.

Just wanted to clarify...
#5

[eluser]Zack Kitzmiller[/eluser]
You can store the error message in a session variable, but I would do that in the controller. It makes for more re-usable code.

In Model:
Code:
function get_name_exists($name){
    $query=$this->db->query("Select * from users where name='".$name."' ;");
        if($query->num_rows()>0){
            return true;
        }
     return false;
}

In Controller
Code:
function some_function() {

    if ($this->some_model->get_name_exists) {
        $this->session->set_userdata('error', 'Username exists');    
    }

}

However, I'd probably tackle this is a completely different way.




Theme © iAndrew 2016 - Forum software by © MyBB