我无法从在数据库
中插入空值的表单中获取post值用户控制器
public function edit($id = NULL) {
if ($id) {
$this->data ['user'] = $this->user_login_model->get($id);
count ( $this->data ['user'] ) or $this->data ['errors'] [] = "user could not be found";
} else {
$this->data ['user'] = $this->user_login_model->new_user ();
}
$rules = $this->user_login_model->rules_admin;
$id || $rules ['password'] .= '|required';
$this->form_validation->set_rules ( $rules );
if ($this->form_validation->run () == TRUE) {
$data=$this->user_login_model->array_from_post(array('name','email','password'));
$this->data['password']=$this->user_login_model->$data['password'];
$this->user_login_model->save($data,$id);
redirect('admin/users');
// do stuff
}
如果是新用户,则会发布新数据
public function new_user() {
$user=new stdClass();
$user->name ='';
$user->email ='';
$user->password ='';
return $user;
var_dump($user);
模型方法,它将遍历数组并返回它
public function array_from_post($fields) {
$data = array ();
foreach ( $fields as $field ) {
$data['feild']=$this->input->post($field);
return $data;
echo var_dump($data);
}
}
这是var_dump
object(stdClass)[22]
public 'id' => string '18' (length=2)
public 'email' => string '' (length=0)
public 'password' => string '' (length=0)
public 'name' => string '12' (length=2)
这是空的,你能告诉我这是什么问题吗?
答案 0 :(得分:0)
你的array_from_post函数基本没用。你有一个return
INSIDE循环,这意味着你在第一次尝试迭代循环时从函数中止循环/返回。因此,您只能返回 ONE 的参数值。
e.g。
array_from_post(array('foo', 'bar'));
foreach(array('foo', 'bar') as $field) {
return $field;
}
您开始循环,foo
被分配到$ field,然后您返回。循环永远不会达到bar
。
你可能想要
public function array_from_post($fields) {
$data = array ();
foreach ( $fields as $field ) {
$data[$field]=$this->input->post($field);
}
return $data;
}
注意$data[$field]
。使用$data['feild']
只会给你一个数组,其中包含一个值,最后一个由循环处理。并注意返回调用是如何循环的。
答案 1 :(得分:0)
试试这个 您的控制器编辑功能
public function edit($id = NULL) {
if ($id)
{
$this->data ['user'] = $this->user_login_model->get($id);
count ( $this->data ['user'] ) or $this->data ['errors'] [] = "user could not be found";
}
else
{
$this->data ['user'] = $this->user_login_model->new_user ();
}
$rules = $this->user_login_model->rules_admin;
$id || $rules ['password'] .= '|required';
$this->form_validation->set_rules ( $rules );
if ($this->form_validation->run () == TRUE)
{
$this->data=$this->user_login_model->array_from_post(array('name','email','password'));
$this->data=$this->array_from_post(array('name','email','password'));
// I removed this line not sure what you did here
$this->user_login_model->save($this->data,$id);
// do stuff
redirect('admin/users');
}
}
你的模型array_from_post函数
public function array_from_post($fields)
{
$data = array ();
foreach ( $fields as $field )
{
$data[$field]=$this->input->post($field);
}
return $data;
}
您的新用户功能
public function new_user() {
$user=new stdClass();
$user->name ='';
$user->email ='';
$user->password ='';
return $user;
}
希望它能帮到你