// application/common/model/User.php
namespace appcommonmodel;
use thinkModel;
class User extends Model
{
// 定义数据表名称
protected $table = 'user';
// 定义可写字段
protected $fillable = ['name', 'email', 'password'];
}
// application/index/controller/UserController.php
namespace appindexcontroller;
use appcommonmodelUser;
use thinkController;
use thinkRequest;
class UserController extends Controller
{
// 显示用户添加表单
public function create()
{
return $this->fetch();
}
// 处理表单提交
public function save(Request $request)
{
$data = $request->post();
// 使用模型创建新用户
User::create($data);
// 重定向到用户列表页面
<!-- application/index/view/user/create.html -->
<form method="post" action="<?php echo url('user/save'); ?>">
<label for="name">姓名:</label>
<input type="text" name="name" id="name" required><br>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email" required><br>
<label for="password">密码:</label>
<input type="password" name="password" id="password" required><br>
<input type="submit" value="添加用户">
</form>
// application/index/controller/UserController.php
// 删除用户
public function delete($id)
{
// 使用模型删除用户
User::destroy($id);
// 重定向到用户列表页面
$this->success('用户删除成功', 'index');
}
<!-- application/index/view/user/index.html -->
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
foreach ($users as $user):
<tr>
<td>echo $user['id']; </td>
<td>echo $user['name']; </td>
<td>echo $user['email']; </td>
<td>
<a href="<?php echo url('user/delete', ['id' => $user['id']]); ?>" onclick="return confirm('确定要删除吗?')">删除</a>
</td>
</tr>
endforeach;
</tbody>
</table>
// application/index/controller/UserController.php
// 显示用户编辑页面
public function edit($id)
{
$user = User::find($id);
return $this->fetch('edit', ['user' => $user]);
}
<!-- application/index/view/user/edit.html -->
<form method="post" action="<?php echo url('user/update', ['id' => $user['id']]); ?>">
<label for="name">姓名:</label>
<input type="text" name="name" id="name" value="<?php echo $user['name']; ?>" required><br>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email" value="<?php echo $user['email']; ?>" required><br>
<label for="password">密码:</label>
<input type="password" name="password" id="password"><br>
<input type="submit" value="更新用户">
</form>
// application/index/controller/UserController.php
// 处理编辑表单提交
public function update(Request $request, $id)
{
$data = $request->post();
// 使用模型更新用户
User::update($data, ['id' => $id]);
// 重定向到用户列表页面
$this->success('用户更新成功', 'index');
}
$users = User::where('age', '>', 18)->select
关 注 有 礼
欢迎关注公众号:网络安全者
原文始发于微信公众号(网络安全者):ThinkPHP5.1中增删改查操作
- 左青龙
- 微信扫一扫
- 右白虎
- 微信扫一扫
评论