我想允许更新或添加新用户,但未能传达如何判断它是新用户还是现有用户的方法。这是我写的代码:
模特:
<?php
类Users_model扩展CI_Model
{
protected $table_name = 'users';
function __construct() {
parent::__construct();
}
public function get_all_users() {
$result = $this->db->query("SELECT * FROM users");
if ($result->num_rows() > 0) {
foreach ($result->result() as $row) {
$data[] = $row;
}
return $data;
}
}
public function get_user_id() {
$this->db->select('*');
$this->db->from('users');
$this->db->where('id', $this->uri->segment(3));
$query = $this->db->get();
return $query->row();
}
public function insert_user($data) {
$this->db->insert('users', $data);
}
public function updata_user($data) {
$this->db->where('id', $this->uri->segment(3));
$this->db->update('users', $data);
}
}
控制器:
function edit () {
$data['user'] = $this->users_model->get_user_id();
$data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $data);
}
public function save() {
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password'),TRUE)
);
if ($this->uri->segment(3) == FALSE) {
$this->users_model->insert_user($data);
}
else {
$result = $this->users_model->updata_user($data);
if ($result) {
redirect('users/index');
}
}
}
观点:
<?php echo validation_errors(); ?>
<?php echo form_open('users/save'); ?>
<table class="table">
<tr>
<td>Name</td>
<td><?php echo form_input('name', set_value('name', $user->name)); ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo form_input('email', set_value('email', $user->email)); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo form_password('password'); ?></td>
</tr>
<tr>
<td>Confirm password</td>
<td><?php echo form_password('password_confirm'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close();?>
答案 0 :(得分:3)
您应该检查:
if ($ this-> uri-> segment (3) == NULL) {
$ this-> users_model-> insert_user ($ data);
redirect ('users / index');
}
还有一个建议是,您应该检查电子邮件的唯一性。
或者另外一种方法是:
我认为这会对你有所帮助。 如果有更多的查询评论它。我会帮助你的。