Welcome Guest, Not a member yet? Register   Sign In
Validating variables in model
#1

[eluser]Jmz[/eluser]
I've made a simple controller and method that updates a record in a db.

The code looks like:
Controller
Code:
function edit(){
        $newval = $this->input->post('newval', TRUE);
        $id = $this->input->post('itemid');
        $user_id = $this->session->userdata('userid');
        if(is_numeric($id) && $newval && is_numeric($user_id))
        {
            $this->load->model('usermodel');
            $data = array(
                            'text' => $newval
                          );
            $where = array(
                        'id' => $id,
                        'user_id' => $user_id
                        );
            if($this->usermodel->edit($data,$where))
            {
                echo "Item updated";
            }else{
                echo "Item could not be updated";
            }
        }else{
            echo "Item could not be updated";    
        }
    }

Model
Code:
function edit($data = NULL, $where = NULL){
        if(count($data) == 1 && count($where) == 2 && $data['text'] && is_numeric($where['id']) && is_numeric($where['user_id']))
        {
            $this->db->where($where);
            if($this->db->update('items',$data))
            {
                return TRUE;
            }else{
                return FALSE;
            }
        }else{
            return FALSE;
        }
    }

First off, is it best practice to validate the data in the model or will it always be valid since it's coming from the controller?

Secondly, instead of using two arrays (one for the data and one for the where clause) could I use a multidimensional array or will that not work?
#2

[eluser]n0xie[/eluser]
It depends on personal preference I guess. I personally validate all the relevant data inside the controller and keep the Model 'dumb'. I.e. all it does is process data without ever validating if the data is actually what it says it is.
#3

[eluser]mi6crazyheart[/eluser]
I think, if we see from MVC working point of view, we should check/control what ever we want in the controller file & leave model are for dirty DB jobs. This way we can provide proper security to our application...




Theme © iAndrew 2016 - Forum software by © MyBB