我正在处理会话数据,当用户在杂货店crud表中输入新记录时,会自动加载电子邮件。在页面顶部,可以使用(在视图文件夹中)
显示当前用户的名称/电子邮件<?php echo $user->email;?>
但是,当我尝试在GC控制器中使用$ user-&gt;电子邮件时,即使在分配给变量后它也会出现错误。还尝试使用set_userdata更改模型但仍然无法工作。代码如下
错误
消息:未定义的变量:user
消息:尝试获取非对象的属性
模型
public function takeUser($username, $password)
{
$this->db->select('*');
$this->db->from('user');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get();
return $query->num_rows();
}
public function userData($username)
{
$this->db->select('username');
$this->db->select('name');
$this->db->select('email');
$this->db->where('username', $username);
$query = $this->db->get('user');
return $query->row();
}
控制器
public function program()
{
if($this->session->userdata('isLogin') == FALSE)
{
redirect('login/login_form');
}
else
{
$this->load->model('m_login');
$user = $this->session->userdata('username');
$data['level'] = $this->session->userdata('level');
$data['user'] = $this->m_login->userData($user);
}
$crud = new grocery_CRUD();
$crud->set_table('program');
$crud>columns('nama_program','kod_program','kos_program','rmk','rollingplan','user','email');
$crud>field_type('nama_program','kod_program','kos_program','rmk','rollingplan','user','email');
$crud>set_relation('rollingplan','rollingplan','nama_rollingplan');
$crud->callback_field('user',array($this,'user_field'));
$crud->callback_field('email',array($this,'email_field'));
$crud->set_subject('Program Baru');
$crud->required_fields('nama_program');
$output = $crud->render();
$this->_example_output_prog($output);
}
function user_field($value = '', $primary_key = null)
{
return '<input type="text" maxlength="50" readonly="readonly" value="'.$this->session->userdata('username').'" name="user" style="width:462px">';
}
function email_field($value = '', $primary_key = null)
{
$mail=$user->email;
return '<input type="text" maxlength="50" readonly="readonly" value="'.$mail.'" name="email" style="width:462px">';
}
答案 0 :(得分:0)
$this->load->model('m_login');
$user='';
if($this->session->userdata('username'))
{
$user = $this->session->userdata('username');
$data['level'] = $this->session->userdata('level');
$data['user'] = $this->m_login->userData($user);
}
else
{
//session expired or not created.
}
使用空白初始化$ user并检查会话变量是否存在。
答案 1 :(得分:0)
如果您使用的是PHP 5.4或更高版本(我认为它适用于PHP 5.3但不确定),您可以使用匿名函数和use
关键字轻松完成。更具体地说,您可以这样做:
public function program() {
...
$crud->callback_field('email',function ($value, $primary_key) use ($user) {
return '<input type="text" maxlength="50" readonly="readonly" value="'.$user.'" name="email" style="width:462px">';
});
...
}
用上述方式: