<?php
namespace app\home\controller;
use think\Controller;
use think\Loader;
class Article extends Controller
{
public function add(){
return view('add_article');
}
public function addArticle(){
$article = input();
array_unshift($article);
$validate = Loader::validate('Article');
if(!$validate->check($article)){
$this->error($validate->getError());
}
$file = request()->file('img');
if($file){
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
if($info){
$article['img'] = DS.'uploads'.DS.$info->getSaveName();
}else{
// 上传失败获取错误信息
$this->error($file->getError());
}
}
$res = \app\home\model\Article::addAll($article);
if ($res){
$this->success('添加成功','/home/article/showArticle');
}else{
$this->error('添加失败');
}
}
public function showArticle(){
$where = [];
$word = input('word')?input('word'):'';
if (!empty($word)){
$where['title'] = ['like',"$word"];
}
$data = \app\home\model\Article::showList($where,$word);
return view('show_article',compact('data'));
}
}
模型:
<?php
namespace app\home\model;
use think\Model;
class Article extends Model
{
protected $table='news';
protected $autoWriteTimestamp=false;
public static function addAll($article){
return self::create($article,true);
}
public static function showList($where,$word){
return self::where($where)->order('addtime','desc')->
paginate('10',false,[
'query'=>['word'=>$word]
]);
}
}
展示页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form>
<input type="text" name="word">
<input type="submit" value="搜素">
</form>
<table class="table">
<tr>
<td><input type="checkbox" class="all"></td>
<td>编号</td>
<td>标题</td>
<td>描述</td>
<td>图片</td>
<td>内容</td>
<td>添加时间</td>
<td>操作</td>
</tr>
{foreach $data as $v}
<tr>
<td><input type="checkbox" class="son"></td>
<td>{$v.id}</td>
<td>{$v.title}</td>
<td>{$v.text}</td>
<td><img src="{$v.img}" alt=""></td>
<td>{$v.content}</td>
<td>{$v.addtime}</td>
<td><a href="">删除</a></td>
</tr>
{/foreach}
</table>
{$data->render()}
</body>
</html>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
</script>
<script>
$(".all").click(function () {
if ($(".all").is(':checked')){
$(".son").prop('checked',true)
}else {
$(".son").prop('checked',false)
}
})
</script>