サマリー:新聞的增刪改查操作練習(xí)代碼,和管理員模塊差不多。通過模版渲染,數(shù)據(jù)輸入,數(shù)據(jù)獲取接收,實(shí)例化模塊,對數(shù)據(jù)庫增加或者對應(yīng)的id記錄進(jìn)行操作。<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/26 &n
新聞的增刪改查操作練習(xí)代碼,和管理員模塊差不多。通過模版渲染,數(shù)據(jù)輸入,數(shù)據(jù)獲取接收,實(shí)例化模塊,對數(shù)據(jù)庫增加或者對應(yīng)的id記錄進(jìn)行操作。
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/26 * Time: 10:04 */ namespace app\admin\controller; use app\admin\controller\Common; use app\admin\model\NewsModel; use think\facade\Request; use think\facade\Session; class News extends Common { public function index() { $news =new NewsModel(); //實(shí)例化新聞模型 $new = $news->order('id','desc') //查詢并按照id降序 ->paginate(5); //按5條分頁 $this->view->new=$new; //查詢數(shù)據(jù)賦值 //渲染新聞列表 return $this->fetch(); } public function add() { //渲染新聞添加界面 return $this->fetch(); } public function upload() { //上傳新聞圖片方法 $file = Request::file('img'); //獲取前臺上傳提交過來的圖片信息 if($info = $file->validate(['ext'=>'jpg,jpeg,png,gif']) //判斷圖片后綴 ->move('upload')){ //移動目錄 return json(['errno'=>0,'data'=>['/upload/'.$info->getSaveName()]]); //返回成功信息 } else { return $file->getError(); //返回錯誤信息 } } public function DoAdd() { //添加操作 $data = Request::param(); //獲取數(shù)據(jù) $data['time'] = time(); //獲取當(dāng)前時間 $data['username'] = Session::get('username'); //獲取管理員名稱 $title = $data['title']; //獲取標(biāo)題,進(jìn)行判斷 //創(chuàng)建模型 驗(yàn)證標(biāo)題是否重復(fù) $news = NewsModel::where('title',$title)->find(); if($news == true){ //提示信息 return ['res'=>0,'msg'=>'新聞標(biāo)題重復(fù)']; } //不重復(fù)存入數(shù)據(jù)庫 $new = new NewsModel(); //實(shí)例化模型 if($new->save($data)){ return ['res'=>1,'msg'=>'添加成功']; }else{ return ['res'=>0,'msg'=>'添加失敗']; } } public function edit() { //接收傳遞過來的ID $newId = Request::param('id'); //通過ID查詢數(shù)據(jù)并傳給變量$new $new = NewsModel::get($newId); //將數(shù)據(jù)賦值到模版 $this->view->new=$new; //渲染編輯頁面 return $this->fetch(); } //編輯更新寫入 public function DoEdit() { //獲取修改后提交的數(shù)據(jù) $data = Request::param(); //實(shí)例化模型 $new = new NewsModel(); //更新操作 $res = $new->save([ 'title' => $data['title'], 'desc' => $data['desc'], 'content' => $data['content'], 'username' => Session::get('username'), 'time' => time(), ],['id'=>$data['id']]); //更新條件 //驗(yàn)證修改結(jié)果 if($res){ return ['res'=>1,'msg'=>'修改成功']; }else{ return ['res'=>0,'msg'=>'修改失敗']; } } public function del() { //獲取要刪除的ID $newId = Request::param('id'); //實(shí)例模型 $new = new NewsModel(); if($new->destroy($newId)){ //返回提示信息 return ['res'=>1,'msg'=>'刪除成功']; }else{ return ['res'=>0,'msg'=>'刪除失敗']; } } }
添削の先生:查無此人添削時間:2019-04-27 17:29:42
先生のまとめ:完成的不錯,cms后臺就是對數(shù)據(jù)庫數(shù)據(jù)進(jìn)行操作。繼續(xù)加油