Tutorial :Codeigniter: Passing form data from view to controller


Which is right? notice in the second option, I'm passing the form values using the $_POST variable. Whereas the first option, I call and assign variables for each form field.

I've seen this ...

<validation code> ....    $todo = array(        'name'=>$this->input->post('title'),        'description'=>$this->input->post('description')  );    $this->Todo_model->add($todo);   

But I've also seen the following ...

$records['email']    = "trim|required|min_length[4]|xss_clean";  ...  ...        $this->validation->set_rules($records);    if ($this->validation->run())  {     $this->account_model->saveAccountSettings("sam", $_POST);     $this->session->set_flashdata('message', 'Done!');                   redirect('account/settings');  } else {  ...  }   


I tend to use a mix of your two examples. I'm pretty sure things like trim won't modify the actual post data, so you can only take advantage of it if you go through the validation framework to get the data. I actually never access POST directly anymore using CI.

Plus I'd be worried in your second example about just shoving POST into my model. What happens if someone clever adds "lastname" to the post data sent in and your db column is named the same? Even though you weren't expecting to deal with that data now you've got unvalidated data coming in. That's why I employ part of your first example and manually pull out the items I want to save into an array first.

So I'd recommend a hybrid.

Normally my code looks something like this:

$fields['email']    = "trim|required|valid_email|min_length[4]|xss_clean";  ...  ...        $this->validation->set_rules($fields);    if ($this->validation->run())  {     $account = new array();     $account['id'] = $accountId; //wherever you get the Id from     $account['email'] = $this->validation->email;       $this->account_model->save($account);     $this->session->set_flashdata('message', 'Done!');                   redirect('account/settings');  } else {  ...  }   


The first option is better easy to read or trace Pass values using post variables is better option


What the real benefit to use this

$account['email'] = $this->validation->email;  

Instead of

$account['email'] = $this->input->post('email');  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »