连接数据库:connect.php
<?php
$servername="localhost";
$username="formbd";
$password="formbd";
$dbname="form";
//创建连接
$conn=newmysqli($servername,$username,$password,$dbname);
//检测连接
if($conn->connect_error){
die("连接失败:".$conn->connect_error);
}
?>
用户注册前端页面:reg.html
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>用户注册页面</title>
</head>
<body>
<formaction="reg.php"method="post">
<p>用户名:<inputtype="text"name="name"></p>
<p>密码:<inputtype="text"name="password"></p>
<p><inputtype="submit"name="submit"value="注册">
<ahref="login.html"><inputtype="button"name="login"value="已有账号,返回登录"></a>
</p>
</form>
</body>
</html>
注册后端处理:reg.php
<?php
header("Content-Type:text/html;charset=utf8");
if(!isset($_POST['submit'])){
exit("错误执行");
}//判断是否有submit操作
$name=$_POST['name'];//post获取表单里的name
$user_password=$_POST['password'];//post获取表单里的password
include('connect.php');//链接数据库
$q="insertintouser(id,username,password)values(null,'$name','$user_password')";//向数据库插入表单传来的值的sql
$sql="select*fromuserwhereusername='$name'";
if(($conn->query($sql))==$name){
echo'用户名已存在';
$result=$conn->query($sql);
/*echo"
<script>
setTimeout(function(){window.location.href='reg.html';},1000);
</script>
";*/
}
else{
$conn->query($q);
echo"注册成功";
echo"
<script>
setTimeout(function(){window.location.href='login.html';},1000);
</script>
";
}
$conn->close();//关闭数据库
?>
用户登录前端页面:login.html
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>登陆</title>
</head>
<body>
<formname="login"action="login.php"method="post">
<p>用户名<inputtype=textname="name"></p>
<p>密码<inputtype=passwordname="password"></p>
<p><inputtype="submit"name="submit"value="登录">
<ahref="reg.html"><inputtype="button"name="reg"value="注册"></a>
</p>
</form>
</body>
</html>
登录后端处理:login.php
<?PHP
header("Content-Type:text/html;charset=utf8");
if(!isset($_POST["submit"])){
exit("错误执行");
}//检测是否有submit操作
include('connect.php');//链接数据库
$name=$_POST['name'];//post获得用户名表单值
$passowrd=$_POST['password'];//post获得用户密码单值
if($name&&$passowrd){//如果用户名和密码都不为空
$sql="select*fromuserwhereusername='$name'andpassword='$passowrd'";//检测数据库是否有对应的username和password的sql
$result=$conn->query($sql);//执行sql
$rows=$result->fetch_assoc();//返回一个数值
if($rows){//0false1true
header("refresh:0;url=success.php");//如果成功跳转至success.php页面
exit;
}else{
echo"用户名或密码错误";
echo"
<script>
setTimeout(function(){window.location.href='login.html';},1000);
</script>
";//如果错误使用js1秒后跳转到登录页面重试;
}
}else{//如果用户名或密码有空
echo"表单填写不完整";
echo"
<script>
setTimeout(function(){window.location.href='login.html';},1000);
</script>";
//如果错误使用js1秒后跳转到登录页面重试;
}
$conn->close();//关闭数据库
?>
登录成功后:success.php
PS:功能未完善
<?php
include'connect.php';
session_start();//声明变量
$username=isset($_SESSION['nmae'])?$_SESSION['name']:"";
?>
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>登陆成功</title>
</head>
<body>
欢迎光临
<?phpecho$username;?>
<?php?>
</body>
</html>
|