Tips:
描述:写一个登陆表单,并实现其注册 + 登录功能。
要求:
1、表单必须和数据库交互。
2、注册和登录功能都必须有
提示:
1、登录成功后需要给回显
1、创建数据库
1、首先在MySql中创建用于存储用户信息的数据库test和数据表user
2、编写代码
1、登录页面index.html
<!--
登录页面
-->
<html>
<head>
<meta charset='utf-8'>
<title>登录</title>
</head>
<body>
<!--登录窗口-->
<b>登录</b>
<form action = 'login.php' method = 'POST'>
<p><span>用户名:</span><input type = 'text' name = 'username'/></p>
<p><span>密码:</span><input type = 'password' name = 'passwd'/></p>
<input type = 'submit' name = '登录'/>
</from>
<!--注册链接-->
<a href = 'register.html'>新用户注册</a>
</body>
</html>
登录界面显示
2、注册页面register.html
<!--注册页面-->
<html>
<head>
<meta charset="utf-8"/>
<title>注册</title>
</head>
<body>
<b>注册</b>
<form action = 'register.php' method = 'POST'>
<p><span>用户名:</span><input type = 'text' name = 'username'/></p>
<p><span>密码:</span><input type = 'password' name = 'passwd'/></p>
<input type = 'submit' name = '注册'/>
</form>
<a href='index.html'>已完成注册</a>
</body>
</html>
注册页面显示
3、登录界面后端login.php
<meta charset="utf-8">
<?php
$conn = mysqli_connect('127.0.0.1','root','123456','test') or die('数据库连接失败');//输出一条消息并退出当前脚本
$user = $_REQUEST['username'];
$passwd = $_REQUEST['passwd'];
$sql = "select * from user where username='$user' and passwd = '$passwd'";
$result = mysqli_query($conn,$sql);
$x = mysqli_fetch_array($result);//以数组返回sql中数据
$row = mysqli_num_rows($result);//表中有数据,则row为1,没有则为0
if($row == 1)
{
echo $x['username'].'登录成功';
}
else
{
echo '登录失败,请重新登录!';
}
?>
4、注册界面后端register.php
<meta charset='utf-8'/>
<?php
// header("Content-type:text/html;charset=utf-8");
$conn = mysqli_connect('127.0.0.1','root','123456','test');
// $conn->set_charset('utf-8');
$user = $_REQUEST['username'];
$passwd = $_REQUEST['passwd'];
// $connect = $_REQUEST['connect'];
$sql = "INSERT INTO user(id, username, passwd)
VALUES(null, '$user', '$passwd')";
mysqli_query($conn,$sql) or die(mysqli_error($conn));
echo('注册成功').'</br>';
echo("<a href = 'index.html'>点击登录</a>");
?>
3、测试
1、注册新用户
2、注册成功
3、查看数据库是否添加新用户
添加成功
4、点击链接登录
新用户abc登录成功
5、不存在的用户登录
显示登录失败,请重新登录
4、过程困难记录
1、代码编写错误
(1)把form写成from,导致数据无法提交到数据库,点登录按钮无反应
(2)<meta写成<mata导致编码出现错误
百度查找答案还以为是php.ini编码出现错误,去把;default_charset = 'UTF-8'改成了default_charset = 'GBK'也没解决问题
最后检查代码,发现是自己拼写出现了错误
2、在文件夹点击index.html后点击登录,发现login.php直接显示源代码
重启phpstudy也没有用
目前搜了很多答案,都没有为什么,但自己试验发现,是需要在浏览器直接输入127.0.0.1访问,点击登录就可以成功。