- 166浏览
- 2022-05-11
ThinkPHP是一个免费开源的,快速、简单的面向对象的轻量级PHP开发框架,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。遵循Apache2开源许可协议发布,意味着你可以免费使用ThinkPHP,甚至允许把你基于ThinkPHP开发的应用开源或商业产品发布/销售。
一、ThinkPHP5实现用户登录,文章评论。
登录验证,文章评论关联,
二、使用步骤
1.创建数据表
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`t_id` int(10) DEFAULT NULL,
`name` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
`pwd` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`nikename` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
`status` enum('0','1') COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '0异常 1正常',
`created_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `comment` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`u_id` int(10) DEFAULT NULL,
`t_id` int(10) DEFAULT NULL,
`comment_content` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `theme` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`u_id` int(10) DEFAULT NULL,
`c_id` int(10) DEFAULT NULL,
`classify` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`title` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`content` text COLLATE utf8_unicode_ci,
`image_url` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`comment_count` int(6) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2.视图层login:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>站三界导航www.zhansanjie.com</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<form action="get-info" method="post">
{:token()}
用户名: <input type="text" name="name">
<br>
密码: <input type="password" name="pwd">
<br>
验证码 <input type="text" name="yzm">
<div><img src="{:captcha_src()}" alt="captcha" onclick="this.src='{:captcha_src()}'" /></div>
<input type="submit" value="登录">
</form>
</body>
</html>
list:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>站三界导航www.zhansanjie.com
</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<h2>今日头条 <a href="/Wx/Users/logout" style="float: right;font-size: 14px;margin-top: 10px">退出登录</a></h2>
<div>
<table class="table table-hover">
<tr>
<th>标题</th>
<th></th>
<th>操作</th>
</tr>
{volist name='list' id='user'}
{volist name="user['comment']" id="sub"}
<tr>
<td>
{$user.title}
<div style="font-size: 10px;margin-top: 10px;color: #9F9F9F">发布时间:{$user.created_at} 类型:{$user.classify} 评论数:{$user.comment_count}</div>
</td>
<td><img src="/uploads/{$user.image_url}" alt="" width="60px" height="60px" class="img-circle"></td>
<td><a href="\theme\detail?id={$user.id}" style="line-height: 50px">详情</a></td>
</tr>
{/volist}
{/volist}
</table>
<div style="font-size: 12px;margin-top: 50px; margin-left: 10px">共有 {$total} 条</div>
</div>
{$page|raw}
</body>
</html>
detail:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>站三界导航www.zhansanjie.com
</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<h2>详情</h2>
<div>
<table class="table table-hover">
{volist name='lists' id='data'}
{volist name="data['comment']" id="su"}
{volist name="data['user']" id="s"}
<tr>
<td style="text-align: center">{$data.title}</td>
</tr>
<tr>
<td>{$data.content}</td>
</tr>
<tr>
<td><input type="button" onclick="createInput()" value="评论 :"/></td>
</tr>
<tr>
<td>{$s.name}:{$su.comment_content}</td>
</tr>
{/volist}
{/volist}
{/volist}
</table>
</div>
<div id="test">
</div>
</body>
</html>
<script>
function createInput()
{
document.getElementById("test").innerHTML = "<form action='get-info' method='post' > 评论:<input type='text' name='comment_content' /> <input type='submit' value='提交' /> </form>";
}
</script>
3.验证器validate:
<?php
namespace app\wx\validate;
use think\Validate;
class Wxs extends Validate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'name' => 'require|max:25|token',
'pwd' => 'require',
'yzm' => 'require|captcha',
];
/**
* 定义错误信息
* 格式:'字段名.规则名' => '错误信息'
*
* @var array
*/
protected $message = [
'name.require' => '姓名必填',
'name.max' => '姓名最多不能超过25个字符',
'name.token' => 'token验证',
'pwd.require' => '密码必填',
'yzm.require' => '验证码必填',
'yzm.captcha' => '验证码错误',
];
}
3.模型层User:
<?php
namespace app\wx\model;
use think\facade\Session;
use think\Model;
class User extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'timestamp';// true 开启;false 关闭
// 创建时间字段自定义
protected $createTime = 'created_at';// 默认create_time
// 更新时间字段自定义
protected $updateTime = 'updated_at';// 默认update_time
// 设置当前模型对应的完整数据表名称
protected $table = 'user';
//用户表多对多关联
public function theme()
{
return $this->belongsTo('Theme');
}
//用户登录
public static function login($data)
{
$user = self::where('status',1)->where('name',$data['name'])->find();
if($user){
if($user['pwd'] == md5($data['pwd'])){
session('name',$user['name']);
session('id',$user['id']);
return 3; //信息正确
}else{
return 2; //密码 错误
}
}else{
return 1; //用户不存在
}
}
//退出登录
public static function logout()
{
Session::delete('name');
Session::delete(('id'));
Session::clear();
}
}
Theme:
<?php
namespace app\wx\model;
use think\facade\Cache;
use think\facade\Debug;
use think\Model;
class Theme extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'timestamp';// true 开启;false 关闭
// 创建时间字段自定义
protected $createTime = 'created_at';// 默认create_time
// 更新时间字段自定义
protected $updateTime = 'updated_at';// 默认update_time
// 设置当前模型对应的完整数据表名称
protected $table = 'theme';
//建立和comment的关联
public function comment()
{
return $this->hasMany('Comment','t_id');//hasOne是一对一
}
//建立和user的关联
public function user()
{
return $this->hasMany('User','t_id');//hasMany是一对多
}
const CACHE_KEY_PREFIX = __CLASS__.'-'.__FILE__.'-id:';
public static function getUserById($id)
{
$cacheKey = self::CACHE_KEY_PREFIX.$id;
//Debug::remark('cache key',$cacheKey);
if(Cache::has($cacheKey)){
$info = Cache::get($cacheKey);
}else{
$info = self::with('user,comment')->where('id','=',$id)->all();
Cache::set($cacheKey,$info,3600);
}
return $info;
}
public static function delUserById($id)
{
$cacheKey = self::CACHE_KEY_PREFIX.$id;
if(self::where('id',$id)->delete()){
Cache::rm($cacheKey);
return true;
}else{
return false;
}
}
}
Comment:
<?php
namespace app\wx\model;
use think\Model;
class Comment extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'timestamp';// true 开启;false 关闭
// 创建时间字段自定义
protected $createTime = 'created_at';// 默认create_time
// 更新时间字段自定义
protected $updateTime = 'updated_at';// 默认update_time
// 设置当前模型对应的完整数据表名称
protected $table = 'comment';
public function theme()
{
return $this->belongsTo('Theme');
}
}
4.控制器Users:
<?php
namespace app\wx\controller;
use app\wx\model\User;
use think\Controller;
use think\Request;
class Users extends Controller
{
public function login()
{
return view('user/login');
}
public function getInfo(Request $request)
{
$data = $request->param();
$result = $this->validate($data,'\app\wx\validate\Wxs',[],false);
if(true !== $result){
dump($result);
exit();
}
if($request->isPost()){
$user = new User();
$data = input('post.');
$num = $user->login($data);
if($num==3){
$this->success('信息正确,正在为您跳转','Wx/Themes/themeList');
}else{
$this->error('用户名或密码有误');
}
}
return $this->fetch('login');
}
public function logout()
{
User::logout();
$this->success('退出成功,正在为您跳转','Wx/Users/login');
}
}
Themes:
<?php
namespace app\wx\controller;
use app\wx\model\Comment;
use app\wx\model\User;
use app\wx\model\Theme;
use think\Controller;
class Themes extends Controller
{
// protected $users;
// protected $comment;
//
// public function __construct(User $user, Comment $comment)
// {
// $this->users = $user;
// $this->comment = $comment;
// }
//列表
public function themeList()
{
// 查询状态为1的用户数据 并且每页显示10条数据
$list = Theme::paginate(5);
// 获取总记录数
$total = $list->total();
// 获取分页显示
$page = $list->render();
// 模板变量赋值
$this->assign('total', $total);
$this->assign('list', $list);
$this->assign('page', $page);
// 渲染模板输出
return $this->fetch('theme/list');
}
//详情
public function detail($id)
{
$lists = Theme::getUserById($id);
// $a = $lists['content'];
// 渲染模板输出
$this->assign('lists',$lists);
return $this->fetch('theme/detail');
}
public function lists()
{
$member=new Theme();
$list=$member->with('user,comment')->find()->toArray();//查询一条ID为15的用户数据;toArray()是将结果转为数组。
$a = [];
foreach($list as $k=>$v){
}
dump($list['comment']);
exit();
}
/**
* 删除指定资源
*
* @param int $id
* @return \think\Response
*/
public function delete(Theme $theme,$id)
{
if($theme->delUserById($id)){
$msg = '删除成功';
}else{
$msg = '删除失败';
}
return $msg;
}
}
Comments:
<?php
namespace app\wx\controller;
use think\Controller;
class Comments extends Controller
{
}
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index($kw='')
{
if($kw !== ''){
$list = \app\demo\model\Login::where('name','like',"%$kw%")->paginate(1,false,['query'=>request()->param()]);
}else{
$list = \app\demo\model\Login::where('id' ,'>' , 1)->paginate(3,false);
}
// 获取分页显示
$page = $list->render();
// 获取总记录数
$total = $list->total();
// 模板变量赋值
$this->assign('kw',$kw);
$this->assign('list', $list);
$this->assign('total', $total);
$this->assign('page', $page);
// 渲染模板输出
return $this->fetch('list/list');
}
public function add()
{
return $this->fetch('login/add');
}
/**
* 显示创建资源表单页.
*
* @return \think\Response
*/
public function addImage(Request $request)
{
$a = new \app\demo\model\Login();
$data['name'] = $request->param('name');
$data['pwd'] = $request->param('pwd');
// 获取表单上传文件 例如上传了001.jpg
$file = $request->file('image');
// 移动到框架应用根目录/uploads/ 目录下
$info = $file->move(Config::get('upload.upload_path'));
if($info){
// 成功上传后 获取上传信息
// 输出 jpg
echo "文件类型:".$info->getExtension();
echo "<br><br>";
// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
echo "上传文件路径:".$info->getSaveName();
echo "<br><br>";
// 输出 42a79759f284b767dfcb2a0197904287.jpg
echo "文件名:".$info->getFilename();
echo "<br><br>";
echo $info->getPathname();
}else{
// 上传失败获取错误信息
echo $file->getError();
}
$data['image'] = $info->getSaveName();
$b = $a->save($data);
if($b){
$this->success('添加成功,跳转到','demo\Login\index');
}else{
$this->error('添加失败');
}
}
版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、本文由会员转载自互联网,如果您是文章原创作者,请联系本站注明您的版权信息。