思路:
在注册页面输入用户的用户名和密码,通过php执行sql语句存储到数据库中,在登录页面中,获取输入框的value值,到数据库中进行比对,如能在数据库中找到该条数据,则验证通过。
1、注册页面要设置name属性,代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
<form method="post" action="register.php" id="form2">
<p>用户名:<input name="uname" type="text" id="uname"/></p>
<p>密 码:<input name="upwd" type="password" id="upwd"/></p>
<input type="submit" value="提交" id="btn">
</form>
</body>
</html>
执行的php程序如下:
<?php
*//防止中文乱码,针对整个php文件*
header("content-type:text/html;charset=utf-8");
*//后端接收用户名和密码*
$uname = $_POST["uname"];
$upwd = $_POST["upwd"];
*//连接数据库(主机名或IP地址,用户名,密码)*
mysql_connect("127.0.0.1","root","root");
*//选择数据库*
mysql_select_db("1127");
*//设置字符集(针对数据库) myqsl_query()让括号里面的sql语句执行,sql语句必须加引号*
mysql_query("set names utf8");
*//在sql语句中,如果你的变量是字符串,必须加引号*
$sql = "select * from user where uname='$uname'";
*// echo $sql;*
*//得到资源*
$res = mysql_query($sql);
*//要把资源变成数组,如果资源为空,那么转为数组也为空*
$arr = mysql_fetch_assoc($res);
*//print_r($arr);*
if($arr){ *//为真,即不为空,说明存在,不能注册*
echo "<script>alert('用户名已存在,请重新注册');window.location.href='register.html'</script>";
}else{
$sql = "insert into user (uname,upwd) values ('$uname','$upwd')";
$res = mysql_query($sql); //如果添加成功返回true
if($res){ *//添加成功,为真*
echo "<script>alert('注册成功');window.location.href='login.html'</script>";
}else{
echo "<script>alert('注册失败')</script>";
}
}
?>
2、注册完成后直接跳转到登录页面,代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form method="post" action="login.php" id="from1">
<p>用户名:<input name="uname" type="text" id="username"/></p>
<p>密 码:<input name="upwd" type="password" id="userpwd"/></p>
<input type="submit" value="登录" id="btn"/>
</form>
</body>
</html>
获取输入框value值进行数据验证,如果验证通过,直接跳转到首页index.html,执行的php程序如下:
<?php
header("content-type:text/html;charset=utf-8");
$username = $_POST["uname"];
$userpwd = $_POST["upwd"];
mysql_connect("127.0.0.1","root","root");
mysql_select_db("1127");
mysql_query("set names utf8");
$sql = "select * from user where uname='$username'";
$res = mysql_query($sql);
$arr = mysql_fetch_assoc($res);
if($arr){ *//如果存在该用户名*
if($userpwd == $arr["upwd"]){ *//如果密码正确,判断后台获取到的密码和数据库里的密码是否一致*
echo "<script>window.location.href='../last/index.php'</script>";
}else{
echo "<script>alert('密码不正确');window.location.href='index.html'</script>";
}
}else{
echo "<script>alert('用户名不正确,请重新输入');window.location.href='login.html'</script>";
}
?>