CodeIgniter3中实现Admin_Podatki页面用户数据的获取、编辑与删除
问题解决步骤:CodeIgniter3 用户数据展示、编辑与删除功能实现
1. 数据库结构确认
先确保用户表(示例表名users)结构正确,参考结构:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `created_at` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. 模型层(application/models/User_model.php)
实现数据查询、更新、删除的核心方法:
<?php class User_model extends CI_Model { // 获取全部用户数据 public function get_all_users() { return $this->db->get('users')->result(); } // 根据ID获取单个用户详情 public function get_user_by_id($id) { return $this->db->get_where('users', ['id' => $id])->row(); } // 更新用户数据 public function update_user($id, $data) { $this->db->where('id', $id); return $this->db->update('users', $data); } // 删除用户 public function delete_user($id) { $this->db->where('id', $id); return $this->db->delete('users'); } } ?>
3. 控制器层(application/controllers/Admin.php)
处理视图渲染、编辑提交、删除请求的逻辑:
<?php class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('user_model'); // 可在此添加管理员权限验证逻辑 } // 渲染用户列表页面 public function podatki() { $data['users'] = $this->user_model->get_all_users(); $this->load->view('Admin_Podatki', $data); } // 编辑用户:渲染编辑页 + 处理表单提交 public function edit_user($id) { $data['user'] = $this->user_model->get_user_by_id($id); if (!$data['user']) show_404(); if ($this->input->post()) { $update_data = [ 'username' => $this->input->post('username'), 'email' => $this->input->post('email') // 如需更新密码,需添加密码加密逻辑,比如使用password_hash() ]; $this->user_model->update_user($id, $update_data); redirect('admin/podatki'); } $this->load->view('Admin_Edit_User', $data); } // 执行用户删除操作 public function delete_user($id) { $this->user_model->delete_user($id); redirect('admin/podatki'); } } ?>
4. 视图层(application/views/Admin_Podatki.php)
展示用户列表并添加操作按钮:
<h1>用户管理</h1> <table border="1" cellpadding="8" cellspacing="0"> <tr> <th>ID</th> <th>用户名</th> <th>邮箱</th> <th>创建时间</th> <th>操作</th> </tr> <?php foreach ($users as $user): ?> <tr> <td><?= $user->id ?></td> <td><?= $user->username ?></td> <td><?= $user->email ?></td> <td><?= $user->created_at ?></td> <td> <a href="<?= site_url('admin/edit_user/' . $user->id) ?>">编辑</a> <!-- 推荐用POST请求执行删除,避免GET误操作 --> <form action="<?= site_url('admin/delete_user/' . $user->id) ?>" method="post" style="display:inline;"> <button type="submit" onclick="return confirm('确定删除该用户?')">删除</button> </form> </td> </tr> <?php endforeach; ?> </table>
5. 关键检查项
- 确认
application/config/database.php中数据库连接信息配置正确 - 若开启CSRF保护,需在表单中使用
<?= form_open() ?>生成表单,或手动添加CSRF令牌字段 - 访问路径:默认路由下通过
your-domain.com/index.php/admin/podatki访问用户列表页
内容的提问来源于stack exchange,提问作者boris123
相关产品推荐
相关产品推荐

