HTML、PHP实战:搭建一个网页登录页面。

一、实验环境。

MySQL5.7.26

FTP0.9.60

Apache2.4.39

我这里用的是PHPstudy小皮一键搭建的。

数据库

二、登录页面。

登录页面前端代码

文件名:denglu.html

<html>
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<form action=./denglu.php method="get">
<p>用户名:<input type=text name=name></p>
<p>密码:<input type=password name=password></p>
<input type=submit value=登录>
</form>	
<a href=http://127.0.0.1/zhuce.html><input type=submit value=注册></a>
</body>
</html>

登录页面后端代码

文件名:denglu.php

<meta charset="UTF-8">
<?php
$username = root;
$password = root;
$ip = 127.0.0.1;
$database = database;
$conn = new mysqli($ip,$username,$password,$database);

$logname = $_GET[name];
$pw = $_GET[password];

$sql = "select * from table_1 where username = $logname and password = $pw";

$res = mysqli_query($conn,$sql);

if($res->num_rows > 0){
	echo 登陆成功。;
}else{
	echo 登录失败。;
}
?>

使用127.0.0.1跟文件名访问网页。

效果演示

可以看到当我们输入用户名:zhangsan 密码:123456 时,后台的数据库能够查询到,所以登录成功。

而当用户名和密码不匹配时则登录失败。

三、注册页面。

注册页面前端代码

文件名:zhuce.html

<html>
	<head>
		<meta charset="UTF-8">
	</head>
	<body>
		<form action="./zhuce.php" method="get">
			用户名:<input type="text" name="name"><br />
			密码:<input type="password" name="password1"><br />
			确认密码:<input type="password" name="password2"<br />
			<input type="submit" value="提交"><br />
		</form>
	</body>
</html>

注册页面后端代码

文件名:zhuce.php

<meta charset="UTF-8">
<?php
$username = root;
$password = root;
$ip = 127.0.0.1;
$database = database;
$conn = new mysqli($ip,$username,$password,$database);
$logname = $_GET[name];
$password1 = $_GET[password1];
$password2 = $_GET[password2];

$sql = "select * from table_1 where username = $logname;";
$res = mysqli_query($conn,$sql);

if($res->num_rows > 0){
	echo 用户已存在,3秒后跳转,请重新输入。;
	header(Refresh:3,http://127.0.0.1/zhuce.html);
}else{
	if($password1 != $password2){
		echo密码不一致。;
	}else{
		$sql = "insert into table_1 value($logname,$password1);";
		if(mysqli_query($conn,$sql)){
			echo注册成功,3秒后返回登录页面。;
			header(Refresh:3,http://127.0.0.1/denglu.html);
		}else{
			echo注册失败。;
		}
	}
}
?>

效果演示

可以看到,当输入数据库中已经存在的用户时,会显示用户已经存在,并且在3秒之后会跳转回原来的页面。

当用户注册时前后两次输入密码不一致时也会出现提示。

当注册成功时,可以看到数据库中新增了对应的用户名及密码。

经验分享 程序员 微信小程序 职场和发展