1. SESSION 登录实战
pdo文件
<?php
$db=[
'type'=>'mysql',
'host'=>'localhost',
'dbname'=>'demo',
'username'=>'root',
'password'=>'root',
'port' =>3306
];
$dsn = $db['type'].':host='.$db['host'].';dbname='.$db['dbname'];
try{
$pdo = new PDO($dsn,$db['username'],$db['password']);
}catch(PDOException $e){
die('连接失败:'.$e->getMessage());
}
派发器文件
<?php
require __DIR__.'/pdo.php';
session_start();
$a = isset($_GET['a'])?$_GET['a']:'login';
//防止用户传的值不受控制
$action = htmlentities((strtolower(trim($action))));
//print_r($a);
switch($a){
// 登录页面
case'login':
include __DIR__.'/login.php';
break;
// 验证登录
case'check':
include __DIR__.'/check.php';
break;
// 退出登录
case'logout':
include __DIR__.'/logout.php';
break;
// 默认操作
default:
include __DIR__.'/index.php';
break;
}
check文件
<?php
if(!empty($_POST['phone'])&& !empty($_POST['password'])){
$phone = $_POST['phone'];
$pwd = $_POST['password'];
$sql ='SELECT * FROM `user` WHERE `phone`=:phone AND `pwd`=:pwd ';
$stmt = $pdo->prepare($sql);
$stmt -> execute(['phone'=>$phone,'pwd'=>$pwd]);
$user= $stmt -> fetch(PDO::FETCH_ASSOC);
print_r( $user);
if (empty($user)){
echo'未找到用户';
}else{
$_SESSION['name']= $user['name'];}
echo'<script>alert("登录成功");location.assign("index.php");</script>';
}
else{
echo '未填写手机号或密码错误 ';
}
退出文件
<?php
session_destroy();
echo'<script>alert("退出成功");location.assign("index.php");</script>';
主页文件
<?php
session_start();
if(isset($_SESSION['name'])){
echo'已登录';
echo'<br>';
echo'<a href="dispatch.php?a=logout">退出</a>';
}else{
echo'<a href="dispatch.php?a=login">未登录</a>';
}
?>
登录页面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h3>用户登录</h3>
<form action="dispatch.php?a=check" method="post">
<p>
<label for="phone">手机号</label>
<input type="phone" name="phone" id="phone">
</p>
<p>
<label for="password">密码</label>
<input type="password" name="password" id="password">
</p>
<p>
<button>提交</button>
</p>
</form>
</body>
</html>
<?php
2. 练熟pdo操作,增删查改(手写)
![]