Codeigniter:将视图中的表单数据传递给控制器​​

问题描述:

这是正确的吗?注意第二个选项,我使用$ _POST变量传递表单值。鉴于第一个选项,我为每个表单字段调用和分配变量。Codeigniter:将视图中的表单数据传递给控制器​​

我已经看到了这个...

<validation code> .... 

$todo = array(
     'name'=>$this->input->post('title'), 
     'description'=>$this->input->post('description') 
); 

$this->Todo_model->add($todo); 

但我也看到了下面......

$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 { 
... 
} 

我倾向于使用你的两个例子的混合。我非常肯定trim这样的东西不会修改实际的发布数据,所以如果你通过验证框架来获取数据,你只能利用它。我实际上从不再使用CI直接访问POST。

另外我会担心在你的第二个例子中,只是推动POST到我的模型。如果有人巧妙地将“姓氏”添加到发送的发布数据中,并且您的数据库列的名称相同,会发生什么情况?即使你现在不打算处理这些数据,但你已经得到了未经验证的数据。这就是为什么我使用了第一个示例的一部分,并且首先手动将要保存的数据保存到数组中。

所以我建议一个混合动力车。

通常我的代码看起来是这样的:

$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 { 
... 
} 
+0

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

这里不理解这条线。 $ account ['email'] = $ this-> validation-> email; 它在做什么?我的意思是我看到它正在验证该领域,第一个领域是在哪里发挥作用? – luckytaxi 2010-01-07 14:37:16

+0

你可以使用$ this-> validation->就像使用$ this-> input-> post('something')一样。在通过验证框架运行后,它会为您提供POST的价值,同时考虑trim和XSS等内容。 – Parrots 2010-01-07 14:44:58

+0

是否必须在第一行定义“某些东西”?看看它说$ fields ['email'] ...就像我只设置了电子邮件的“验证规则”,我可以做$ this-> validation-> id,是吗? – luckytaxi 2010-01-07 14:49:27

第一个选项是更好易于阅读或跟踪 值传递使用后期变量是更好的选择

什么真正的好处使用相反的

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

这是一个很好的习惯,就是使用一个暗示该值已被验证的语法来取值 – 2011-08-09 00:59:22