1.成品:
创建的数据库信息:
1.login.php
登入界面 输入admin/123
2.点击个人中心 跳转到index.php
2.代码
login.php
<?php
include ('./mysql.php');
if (isset($_POST['submit'])){
if($_POST['username']!= null and $_POST['password'] != null)
{
if(isset($_POST['username']) && isset($_POST['password'])){
$username=$_POST['username'];
$password=$_POST['password'];
echo "欢迎您,".$username;
$sql = "select * from user where name='{$username}' and password='{$password}'";
if ($result = mysqli_query($GLOBALS['link'], $sql) ){
if (mysqli_num_rows($result)>0){
setcookie('name',$username);
echo "登入成功,返回<a href='./index.php'>个人中心</a>";
}else
echo "用户或密码错误1,请<a href='login.php'> 重新登入</a>";
}else
echo "用户或密码错误2,请<a href='login.php'> 重新登入</a>";
}else
echo "输入用户或密码为空,请<a href='login.php'> 重新登入</a>";
}else
{
echo "请输入账号和密码!";
}
}else{
$a=<<<HTML
<html>
<head>
<title>博客</title>
</head>
<body>
<form action="#" method="post" >
用户名:<input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit" name="submit"><br>
</form>
</body>
</html>
HTML;
echo $a;
}
?>
小tips
再调用mysql.php 的$link 老是报错 解决办法:
用:
mysqli_query($GLOBALS['link'], $sql)
解释:
$link在GLOBAL范围内不能从函数直接调用,需要将
$result = mysqli_query($conn,$sql);
替换为$result = mysqli_query($GLOBALS['link'],$sql);
index.php
<?php
if (isset($_COOKIE['name'])){
echo "欢迎您,{$_COOKIE['name']}";
}
else{
echo "用户或密码错误,请<a href='./login.php'>返回登入</a>";
}
?>
删除cookie
mysql.php
<?php
$db_host="127.0.0.1";
$db_username="root";
$db_password="123456";
$db_name="yuchen";
$link = @mysqli_connect($db_host,$db_username,$db_password,$db_name);
if (mysqli_connect_error($link)){
die("连接mysql失败:".mysqli_connect_error());
}
?>
未完待续。。。
添加了一个注册操作
注册
输入aaa 123
数据库查询
register.php:
<?php
include ('./mysql.php');
if (isset($_POST['submit']) ){
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($username == "" || $password == "" | $password2 == ""){
echo "<script>alert('请检查信息完整性!'); history.go(-1);</script>";
}else
{
if ($password == $password2){
$sql_insert = "insert into user (name,password) values('{$username}','{$password}')";
if ($result = mysqli_query($GLOBALS['link'], $sql_insert) )
echo "<script>alert('注册成功!'); history.go(-1);</script>";
else
echo "<script>alert('系统繁忙,稍后重试!'); history.go(-1);</script>";
}else
echo "<script>alert('密码不一致!,请重新输入'); history.go(-1);</script>";
}
}else{
$a=<<<HTML
<html>
<head>
注册界面
</head>
<body>
<form action="#" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
再次输入密码:<input type="password" name="password2"><br>
<input type="submit" name="submit" value="注册">
</form>
</body>
</html>
HTML;
echo $a;
}
?>
这里的sql 语句要和数据库的字段对应,测试了好几次发现是数据库字段值 name 写成了user,另外很多安全机制没考虑,未完待续。
|