零基础可搭建校园新闻发布系统,核心是理清数据“来、存、改、删”四步逻辑;ThinkPHP 5.0 通过模型封装数据库操作,无需手写 SQL,建表后调用 News 模型即可实现增删改查,配合控制器与 Layui 前端快速完成全功能开发。

零基础也能搭出可用的校园新闻发布系统。关键不是写多少代码,而是理清“数据怎么来、怎么存、怎么改、怎么删”这四步逻辑。ThinkPHP 5.0 把这些操作封装得足够简单,你不需要手写 SQL,也不用反复连接数据库,模型(Model)一调就通。
先建好新闻数据表
系统跑起来前,得有地方存新闻。在 MySQL 里执行下面这段 SQL 创建 news 表:
CREATE TABLE `news` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL COMMENT '标题', `author` varchar(50) NOT NULL COMMENT '作者', `content` text NOT NULL COMMENT '内容', `category_id` tinyint(2) DEFAULT '1' COMMENT '分类ID', `addtime` int(11) DEFAULT NULL COMMENT '发布时间(时间戳)', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
注意:addtime 存时间戳(int 类型),比 datetime 更易处理;category_id 默认填 1,方便后续扩展栏目分类。
用模型快速实现增删改查
在 ThinkPHP 中,所有数据库操作都通过模型完成。新建 application/common/model/News.php:
<?php namespace app\common\model;
use think\Model;
class News extends Model
{
// 允许写入字段(防注入)
protected $allowField = ['title', 'author', 'content', 'category_id', 'addtime'];
}</?>有了这个模型,增删改查就能直接用了:
- 新增:$news = new \app\common\model\News(); $news->data(['title'=>'迎新通知','author'=>'校办','content'=>'9月1日报到...','addtime'=>time()])->save();
- 查询全部:$list = \app\common\model\News::all(['status'=>1], 'addtime desc', 10);
- 查单条:$one = \app\common\model\News::get(5);
- 修改:$one = \app\common\model\News::get(5); $one->title = '更新后的标题'; $one->save();
- 删除:\app\common\model\News::destroy(5); 或批量删:News::destroy([1,2,3]);
控制器里组织业务逻辑
在 application/index/controller/News.php 写功能入口:
<?php namespace app\index\controller;
use app\common\model\News;
use think\Controller;
class News extends Controller
{
// 列表页
public function index()
{
$list = News::order('addtime desc')->paginate(10);
$this->assign('list', $list);
return $this->fetch();
}
// 添加页
public function add()
{
if ($this->request->isPost()) {
$data = input('post.');
$data['addtime'] = time();
$res = News::create($data);
if ($res) {
$this->success('发布成功', 'index/news/index');
} else {
$this->error('发布失败');
}
}
return $this->fetch();
}
// 编辑页
public function edit($id)
{
$info = News::get($id);
if (!$info) $this->error('新闻不存在');
if ($this->request->isPost()) {
$data = input('post.');
$info->save($data);
$this->success('更新成功', 'index/news/index');
}
$this->assign('info', $info);
return $this->fetch();
}
// 删除(建议用 AJAX 调用)
public function del($id)
{
if (News::destroy($id)) {
return json(['code'=>1, 'msg'=>'删除成功']);
} else {
return json(['code'=>0, 'msg'=>'删除失败']);
}
}
}对应建好模板文件:application/index/view/news/index.html(列表)、add.html(添加表单)、edit.html(编辑表单),用 {$list} 和 {$info} 直接输出即可。
前端页面加个简洁表单
以添加页面为例,用 Layui 快速搭一个带验证的表单(无需引入 Bootstrap):
<script src="__STATIC__/layui/layui.js"></script><script>layui.use('form', function(){ var form = layui.form; });</script>提交后自动跳转回列表页,错误提示也由 ThinkPHP 的 success/error 方法统一处理,不用自己写 JS 弹窗。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











