ThinkPHP数据添加与显示功能概述
接下来的系列文章将聚焦于ThinkPHP框架的实际应用,直接切入核心内容。本文将演示如何利用该框架完成两项关键任务:一是向数据库插入新数据,二是在前端页面中呈现这些数据。具体目标是用户在add页面录入信息后,能够在lists页面查看到新增记录。需要特别注意的是,由于ThinkPHP框架内部已占用“list”这一字段名,因此在命名HTML模板文件时,严禁使用类似“list.html”的名称,以免产生冲突。预期的界面效果如下所示:

为实现上述功能,我们将遵循MVC(Model-View-Controller)架构设计模式进行开发。首先从视图层(View)入手,利用HTML表单来收集用户输入的数据,具体的代码实现如下:
<form role="form" method="post" action="__MODULE__/Admin/User/doAdd">
<span class="input-group-addon">用<img src="__PUBLIC__/end/images/em.png" alt="" width="6" height="20">户<img src="__PUBLIC__/end/images/em.png" alt="" width="6" height="20">名:</span>
<input type="text" class="form-control" placeholder="" name="username">
<span class="input-group-addon" for="inputWarning1">真实姓名:</span>
<input type="text" class="form-control" placeholder="" id="input" name="realname">
<span class="input-group-addon">手机号码:</span>
<input type="text" class="form-control" placeholder="" name="telphone">
<span class="input-group-addon">电子邮箱:</span>
<input type="text" class="form-control" placeholder="" name="email">
<span class="input-group-addon">添加时间:</span>
<input type="text" class="form-control" placeholder="2014-05-22" name="resgistertime">
<span class="input-group-addon">设置密码:</span>
<input type="text" class="form-control" placeholder="123456" name="password">
<span class="input-group-addon">确认密码:</span>
<input type="text" class="form-control" placeholder="123456" name="repassword">
<button type="submit" class="btn btn-primary "> 保<img src="__PUBLIC__/end/images/em.png" alt="" width="20" height="20">存 </button>
</form>
随后是模型层(Model)的处理部分。目前对这部分的理解主要是用于校验数据的合法性,并在发现错误时提供相应的提示信息。相关的实现代码如下:
<?php
namespace Admin\Model;
use Think\Model;
class AdminUsersModel extends Model {
public $_validate = array (
array("username", "require", "用户名不能为空"),
array("realname", "require", "真实姓名不能为空"),
array("password", "require", "密码不能为空"),
array("repassword", "require", "确认密码不能为空"),
array("telphone", "require", "电话不能为空"),
array("email", "require", "邮箱不能为空"),
array("resgistertime", "require", "注册时间不能为空")
);
}
最后是控制器层(Controller),它主要负责纯粹的逻辑控制。具体的代码实现如下:
public function add(){
$this->display();
}
public function doAdd(){
if (!IS_POST) {
exit("bad request!");
}
$adminUsersModel = D("AdminUsers");
if (!$adminUsersModel->create()) {
$this->error($adminUsersModel->getError());
}
if ($adminUsersModel->add()) {
$this->success("添加成功!",U("Admin/User/lists"));
}
else{
$this->error("添加失败!");
}
}
至此,整个数据添加与显示的完整流程已经阐述完毕,希望这对大家的学习有所帮助。如需进一步查阅,可参考ThinkPHP官方手册:http://document.thinkphp.cn/manual_3_2.html
原文作者:橙色时光