实例整体结构
check.php
:登陆检查control.php
:控制台页(含分页功能)db.php
:数据库连接index.php
:主页login.php
:登录页personal.php
:个人中心页rcheck.php
:注册检查register.php
:注册页面edit.php
:编辑页面handle.php
:功能分配
代码
check.php
:登陆检查
<?php
// 处理登录提交
$username = $_POST['username'];
$password = sha1($_POST['password']);
$remember = $_POST['rem'];
// 连接数据库
require 'db.php';
// PDO查询数据库
$select = "SELECT `id`,`user_name`,`password` FROM `user` WHERE `user_name`=:username AND `password`=:pwd";
$data = $pdo->prepare($select);
$data->bindParam(':username', $username);
$data->bindParam(':pwd', $password);
$data->execute();
$res = $data->fetch(PDO::FETCH_ASSOC);
// 根据查询结果验证登陆数据及是否记住密码
if ($data->rowCount() == 1) {
// 清理已有的cookie
setcookie('username', '', time() - 3600);
setcookie('auth', '', time() - 3600);
// 如果选择了记住密码
if ($remember == 'on') {
setcookie('username', $username, strtotime('+7 days'));
// 加盐生成令牌
$salt = '小刚';
$auth = sha1($username . $password . $salt) . ',' . $res['id'];
setcookie('auth', $auth, strtotime('+7 days'));
} else {
setcookie('username', $username);
$salt = '小刚';
$auth = sha1($username . $password . $salt) . ',' . $res['id'];
setcookie('auth', $auth);
}
exit("<script>
alert('登陆成功');
location.href = 'index.php';
</script>");
} else {
exit("<script>
alert('登陆失败');
location.href = 'login.php';
</script>");
}
control.php
:控制台页(含分页功能)
<?php
require "db.php";
$select = "SELECT `id`,`user_name`,`password`,`user_type` FROM `user`";
$data = $pdo->prepare($select);
$data->execute();
$res = $data->fetchAll();
if ($data->rowCount() == 0) {
exit("<script>
alert('查询失败')
</script>");
}
// 分页
// 1.每页显示数量
$num = 1;
// 2.当前页码,默认为1
$page = $_GET['p'] ?? 1;
// 3.计算每页第一条记录偏移量
$offset = ($page - 1) * $num;
// 4.获取分页数据
$pagedata = "SELECT * FROM `user` LIMIT {$num} OFFSET {$offset}";
// 语句简写
// $pagedata = "SELECT * FROM `user` LIMIT {$offset}, {$num}";
$users = $pdo->query($pagedata)->fetchAll();
// 5.计算总页数
// 计算表中共计有多少条记录,每页显示几条
// 总页数=ceil(记录总数/每页的记录数):ceil()向上取整函数
$sql = "SELECT CEIL(COUNT(`id`)/{$num}) AS `total` FROM `user`";
$pages = $pdo->query($sql)->fetch()['total'];
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="layui/css/layui.css" media="all" />
<title>控制台</title>
</head>
<style>
body {
min-width: 1000px;
}
.tab {
width: 900px;
margin: 0 auto;
}
.container {
width: 500px;
margin: 0 auto;
}
.pag {
font-size: 0;
margin: 10px auto;
}
.pag > li {
display: inline-block;
min-width: 30px;
height: 20px;
font-size: 16px;
}
.pag > li > a {
display: block;
line-height: 20px;
text-align: center;
padding: 5px;
border: 1px solid gray;
}
.pag > li > a:hover {
color: white;
background-color: teal;
}
.active {
color: white;
background-color: teal;
}
</style>
<body>
<table class="layui-table tab">
<colgroup>
<col width="150">
<col width="200">
<col>
</colgroup>
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>用户类型</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?foreach ($users as $user):?>
<tr>
<td><?echo $user["id"]?></td>
<td><?echo $user["user_name"]?></td>
<td><?echo $user["password"]?></td>
<td><?echo $user["user_type"] == 1 ? "管理员" : "非管理员"?></td>
<td>
<button class="layui-btn layui-btn-xs" onclick="location.href='handle.php?action=edit&userid=<?=$user['id']?>'">编辑</button>
<button class="layui-btn layui-btn-xs layui-btn-warm" onclick="location.href='handle.php?action=del&userid=<?=$user['id']?>'">删除</button>
</td>
</tr>
<?endforeach?>
</tbody>
</table>
<div class="container">
<ul class="pag">
<li><a href="<?=$_SERVER['PHP_SELF']. '?p=1'?>">首页</a></li>
<?php
// 上一页
$prev = ($page-1) == 0 ? 1 : ($page-1);
// 下一页
$next = ($page+1) > $pages ? $pages : ($page+1);
?>
<li><a href="<?=$_SERVER['PHP_SELF']. '?p='. $prev?>">上一页</a></li>
<?php for ($i=1; $i<=$pages; $i++): ?>
<?php
// $i是分页条中的页码,$page是url中get获取到的页码
$active = ($i == $page) ? 'active' : null;
// $_SERVER['PHP_SELF']是全局变量中的url地址,做字符串拼接get请求参数
// $jump = $_SERVER['PHP_SELF']. '?p='. $i;
// 可以用sprintf()拼接url字符串
$jump = sprintf("%s?p=%s", $_SERVER['PHP_SELF'], $i);
?>
<li><a href="<?=$jump?>" class="<?=$active?>"><?=$i?></a></li>
<?php endfor ?>
<li><a href="<?=$_SERVER['PHP_SELF']. '?p='. $next?>">下一页</a></li>
<li><a href="<?=$_SERVER['PHP_SELF']. '?p='. $pages?>">尾页</a></li>
</ul>
</div>
<script src="layui/layui.js" charset="utf-8"></script>
</body>
</html>
db.php
:数据库连接
<?php
// 配置mysql数据库连接参数
define('DB_HOST', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'phptest');
define('DB_USER', 'root');
define('DB_PWD', '123456');
define('DB_TYPE', 'mysql');
define('DB_CHARSET', 'utf8');
// 配置PDO连接数据库参数,DSN:datasoursename
define('DB_DSN', DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET);
// 捕获错误,比较消耗资源
try {
$pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
// 抛出一个 PDOException 异常
} catch (PDOException $e) {
echo $e->getMessage();
// 捕获拥有Throwable接口的错误或者其他异常
} catch (Throwable $e) {
echo $e->getMessage();
}
// 可设置默认以索引数组方式获取结果集
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
index.php
:主页
<?php
// 连接数据库
require 'db.php';
$token = $_COOKIE['auth'];
$auth_true = explode(',', $token)[0];
$id = end(explode(',', $token));
$select = "SELECT `id`,`user_name`,`password` FROM `user` WHERE `id`=:id";
$data = $pdo->prepare($select);
$data->bindParam(':id', $id);
$data->execute();
$res = $data->fetch();
if ($data->rowCount() === 1) {
$username = $res['user_name'];
$password = $res['password'];
$salt = '小刚';
$auth = sha1($username . $password . $salt);
if ($auth_true !== $auth) {
exit("<script>
alert('未登录');
location.href='login.php';
</script>");
}
} else {
exit("<script>
alert('请先登录');
location.href='login.php';
</script>");
}
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="layui/css/layui.css" media="all" />
<title>主页</title>
</head>
<style>
body {
margin: 0 30px;
}
</style>
<body>
<ul class="layui-nav">
<li class="layui-nav-item">
<a href="control.php" target="_blank">控制台<span class="layui-badge">9</span></a>
</li>
<li class="layui-nav-item">
<a href=<?php echo "personal.php"."?username={$username}" ?> target="_blank">个人中心<span class="layui-badge-dot"></span></a>
</li>
<li class="layui-nav-item layui-layout-right" lay-unselect="">
<a href="javascript:;"><img src="face.jpg" class="layui-nav-img">
<?php echo $_COOKIE['username']; ?>
</a>
<dl class="layui-nav-child">
<dd><a href="javascript:;">修改信息</a></dd>
<dd><a href="javascript:;">修改密码</a></dd>
<dd><a href="login.php?action=logout">退出</a></dd>
</dl>
</li>
</ul>
</body>
<script src="layui/layui.js" charset="utf-8"></script>
<script>
layui.use('element', function() {
//导航的hover效果、二级菜单等功能,需要依赖element模块
var element = layui.element;
});
</script>
</html>
login.php
:登录页
<?php
// 退出清cookie
if ($_GET['action'] == 'logout') {
setcookie('username', '', time() - 3600);
setcookie('auth', '', time() - 3600);
exit("<script>
location.href='login.php';
</script>");
}
// 连接数据库
require 'db.php';
$token = $_COOKIE['auth'];
$auth_true = explode(',', $token)[0];
$id = end(explode(',', $token));
$select = "SELECT `id`,`user_name`,`password` FROM `user` WHERE `id`=:id";
$data = $pdo->prepare($select);
$data->bindParam(':id', $id);
$data->execute();
$res = $data->fetch();
if ($data->rowCount() == 1) {
$username = $res['user_name'];
$password = $res['password'];
$salt = '小刚';
$auth = sha1($username . $password . $salt);
if ($auth_true == $auth) {
exit("<script>
alert('已登陆');
location.href='index.php';
</script>");
}
}
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="layui/css/layui.css" />
<title>登录页</title>
</head>
<style>
.container {
width: 400px;
min-height: 400px;
margin: 100px auto;
}
</style>
<body>
<form class="layui-form container" action="check.php" method="POST">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="username" lay-verify="required" lay-reqtext="用户名是必填项" placeholder="请输入用户名" autocomplete="off" class="layui-input" />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" name="password" lay-verify="required" lay-reqtext="密码是必填项" placeholder="请输入密码" autocomplete="off" class="layui-input" />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">记住密码</label>
<div class="layui-input-block">
<input type="checkbox" name="rem" lay-skin="switch" lay-filter="switchTest" lay-text="开启|关闭" />
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="login">
登陆
</button>
<a href="register.php" class="layui-btn layui-btn-normal" target="_blank">注册</a>
</div>
</div>
</form>
</body>
<script src="layui/layui.js" charset="utf-8"></script>
<script>
layui.use(["form"], function() {
var form = layui.form,
layer = layui.layer;
});
</script>
</html>
personal.php
:个人中心页
<?php
require "db.php";
$username = $_GET['username'];
$select = "SELECT `id`,`user_name`,`password`,`user_type` FROM `user` WHERE `user_name`=:username";
$data = $pdo->prepare($select);
$data->bindParam(':username', $username);
$data->execute();
$res = $data->fetch();
if ($data->rowCount() !== 1) {
exit("<javascript>
alert('用户不存在')
</javascript>");
}
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="layui/css/layui.css" />
<title>个人中心</title>
</head>
<style>
.container {
width: 400px;
min-height: 400px;
margin: 100px auto;
}
</style>
<body>
<form class="layui-form container" action="javascript:void(0)" method="POST">
<div class="layui-form-item">
<label class="layui-form-label">ID</label>
<div class="layui-input-block">
<input type="text" name="userid" autocomplete="off" class="layui-input" value=<?echo $res["id"]?> disabled />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="username" autocomplete="off" class="layui-input" value=<?echo $res["user_name"]?> disabled />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" name="password" autocomplete="off" class="layui-input" value=<?echo $res["password"]?> disabled />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">用户类型</label>
<div class="layui-input-block">
<input type="text" name="usertype" autocomplete="off" class="layui-input" value=<?echo $res["user_type"] == 1 ? "管理员" : "非管理员"?> disabled />
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="login" onclick="window.close()">
关闭
</button>
</div>
</div>
</form>
</body>
<script src="layui/layui.js" charset="utf-8"></script>
<script>
layui.use(["form"], function() {
var form = layui.form,
layer = layui.layer;
});
</script>
</html>
rcheck.php
:注册检查
<?php
// 处理注册提交
$username = $_POST['username'];
$password = sha1($_POST['password']);
// 连接数据库
require 'db.php';
// PDO查询数据库
$select = "SELECT `id`,`user_name` FROM `user` WHERE `user_name`=:username";
$data = $pdo->prepare($select);
$data->bindParam(':username', $username);
$data->execute();
$res = $data->fetch();
// 根据查询结果验证注册数据
if ($data->rowCount() == 1) {
// 如果已经存在用户
exit("<script>
alert('用户已存在');
location.href = 'register.php';
</script>");
}
$insert = "INSERT INTO user(`user_name`,`password`) VALUES(:username,:pwd)";
$data = $pdo->prepare($insert);
$data->bindParam(':username', $username);
$data->bindParam(':pwd', $password);
$data->execute();
$res = $data->fetch();
if ($data->rowCount() == 1) {
// 如果插入数据成功
exit("<script>
alert('注册成功');
location.href = 'login.php';
</script>");
}else {
exit("<script>
alert('注册失败');
location.href = 'register.php';
</script>");
}
register.php
:注册页面
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="layui/css/layui.css" />
<title>注册页</title>
</head>
<style>
.container {
width: 400px;
min-height: 400px;
margin: 100px auto;
}
</style>
<body>
<form class="layui-form container" action="rcheck.php" method="POST">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="username" lay-verify="required" lay-reqtext="用户名是必填项" placeholder="请输入用户名" autocomplete="off" class="layui-input" />
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" name="password" lay-verify="required" lay-reqtext="密码是必填项" placeholder="请输入密码" autocomplete="off" class="layui-input" />
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="login">
提交
</button>
</div>
</div>
</form>
</body>
<script src="layui/layui.js" charset="utf-8"></script>
<script>
layui.use(["form"], function() {
var form = layui.form,
layer = layui.layer;
});
</script>
</html>
edit.php
:编辑页面
<?php
$edit = $pdo->query("SELECT * FROM `user` WHERE `id`={$userid}")->fetch();
?>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="layui/css/layui.css" media="all" />
<title>编辑表单</title>
</head>
<style>
.container {
width: 400px;
min-height: 200px;
margin: 100px auto;
}
</style>
<body>
<fieldset class="layui-elem-field container">
<legend>编辑用户</legend>
<div class="layui-field-box">
<form class="layui-form" action="<?php echo $_SERVER['PHP_SELF']. '?action=doedit&userid='. $edit['id']; ?>" method="POST">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="username" required lay-verify="required" autocomplete="off" class="layui-input" value="<?=$edit['user_name']?>">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" name="password" required lay-verify="required" autocomplete="off" class="layui-input" placeholder="请输入新密码">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="formDemo">保存</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
</div>
</fieldset>
</body>
<script src="layui/layui.js" charset="utf-8"></script>
<script>
layui.use('form', function(){
var form = layui.form;
//监听提交
// form.on('submit(formDemo)', function(data){
// layer.msg(JSON.stringify(data.field));
// return false;
// });
});
</script>
</html>
handle.php
:功能分配
<?php
require "db.php";
$action = $_GET['action'];
$userid = $_GET['userid'];
switch ($action) {
case 'edit':
// 加载、渲染数据编辑表单
include 'edit.php';
break;
case 'doedit':
$doedit = "UPDATE `user` SET `user_name`=?, `password`=? WHERE `id`=?";
$stmt = $pdo->prepare($doedit);
if (!empty($_POST)) {
$pwd = sha1($_POST['password']);
$stmt->execute([$_POST['username'], $pwd, $userid]);
echo $stmt->rowCount() == 1 ? "<script>alert('修改成功!');location.href='control.php';</script>" : "<script>alert('修改失败!');location.href='control.php';</script>";
}
break;
case 'del':
$del = "DELETE FROM `user` WHERE `id`=?";
$data = $pdo->prepare($del);
$data->execute([$userid]);
if ($data->rowCount() == 1) {
exit("<script>alert('删除成功');location.href='control.php';</script>");
} else {
exit("<script>alert('删除失败');location.href='control.php';</script>");
}
break;
}
功能演示
- 记住密码登陆:
- 退出登录再直接进入主页提示先登陆:
- 注册后登陆:
- 渲染数据:
- 简单分页:
- 上一页、下一页;
- 首页、尾页;
- 编辑:
- 删除:
总结
将PDO预处理操作数据库和会话控制整合到实际案例中做了个大作业,还加入了分页功能,希望老师别打我呀:)
提前预习了下前端框架layui的使用,感觉很强大,但有一定局限性。