PHP连接mysql数据库注册登录验证

1、首先在mysql命令控制台新建数据库

mysql> create database test;
Query OK, 1 row affected (0.04 sec)

mysql> use test;
Database changed

mysql> create table test_table(
-> id int(5) auto_increment primary key,
-> user char(10),
-> pass char(10),
-> text char(10),
-> sex char(1),
-> connect char(10));
Query OK, 0 rows affected (0.21 sec)

mysql>
2、登录注册代码

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<div>
<b>登录</b>
<form action="login.php" method="post">
<p><span>用户名:</span><input type="text" name="user" required="" /></p>
<p><span>密码:</span><input type="password" name="pass"/ required=""></p>
<p><input type="reset" name=""/> <input type="submit" name=""/></p>
</form>
<a href="register.html">新用户注册</a>
</div>
</body>
</html>
register.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<div>
<b>注册</b>
<form action="register.php" method="post">
<p><span>用户名:</span><input type="text" name="user" required=""/></p>
<p><span>密码:</span><input type="password" name="pass" required=""/></p>
<p><span>性别:</span>
<input type="radio" name="sex" checked="checked" value="男"/>男
<input type="radio" name="sex" value="女"/>女
</p>
<p><span>联系:</span><input type="text" name="connect" value="" required=""/></p>
<p><span>文本:</span><input type="text" name="text" required=""/></p>
<p><input type="reset" name=""/> <input type="submit" name=""/></p>
</form>
<a href="index.html">已注册</a>
</div>
</body>
</html>
login.php

<meta charset="utf-8">
<?php
try {
$conn = new mysqli('localhost', 'root', '','test');
}
catch (Exception $e) {
die("数据库连接失败");
}
$conn->query("SET NAMES 'UTF8'");
$user = $_POST['user'];
$pass = $_POST['pass'];
$sql="SELECT * FROM test_table where user='$user' and pass='$pass'";
$rs=$conn->query($sql);
$row = $rs-> fetch_array();
// var_dump($row);
if($row['user']==$user&& $row['pass']==$pass){
echo $row['user']."登陆成功!";
}
else{
echo"登录失败,请重新登录!";
}
?>
register.php

<?php
header ( "Content-type:text/html;charset=utf-8" );
try {
$conn = new mysqli('localhost', 'root', '','test');
}
catch (Exception $e) {
die("数据库连接失败");
}
$conn->query("SET NAMES 'UTF8'");
$user = $_POST['user'];
$pass = $_POST['pass'];
$sex = $_POST['sex'];
$connect = $_POST['connect'];
$text = $_POST['text'];
$sql = "INSERT INTO test_table VALUES ('','{$user}' ,'{$pass}','{$text}','{$sex}' ,'{$connect}' )";
$result = $conn->query($sql);
// if ($result > 0) {
// echo "<script> alert('注册成功,返回登录页面');
// window.location='index.html'; //跳转到注册页
// </script>";
// } else {
// echo "<script> alert('注册失败,返回注册页面');
// window.history.back(); //返回上一页
// </script>";
// }
echo("注册成功!!!<br/><a href='index.html'>点击登录</a>")

转载:https://blog.csdn.net/cai181191/article/details/79341614

posted @ 2020-07-19 16:10  Adam_101  阅读(123)  评论(0编辑  收藏  举报