哪个是对的?注意在第二个选项中,我使用 $_POST 变量传递表单值。而第一个选项,我为每个表单字段调用和分配变量。
我见过这个...
<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 {
...
}
关于Codeigniter:将表单数据从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2020863/