0
点赞
收藏
分享

微信扫一扫

PHP和HTML登陆页实现单页面显示登录数据库成败的状态

田妞的读书笔记 2022-02-02 阅读 68
php

上文的登录框在提交表单后显示登录状态时,表单就消失了。本文实现登录后仍然停留在登录页。

上代码:

//index.php
<?php
header('Location: login.php');
?>

这个就是实现到登陆页的定向。

//login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>Insert title here</title>
</head>
<body>
<form action="check_login.php" name="loginform"  method="post">
帐号:
  <input type="text" name="name" />
密码:
  <input type="password" name="pwd" />
<input type="submit" value="登 录" />
</form>
<?php
echo "<br/>";
//通过 error 值,确定提示信息
if(!empty($_GET['error'])){
  $error=$_GET['error'];
  If($error==1){
    Echo "<font color ='red'>您输入的账号或密码错误!</font>";
  }elseif ($error==2){
    Echo "<font color ='red'>您输入的账号或密码正确!</font>";
  }
}
?>
</body>
</html>

通过error信息的设置来决定状态的显示。

//check_login.php
<?php
header("Content-type: text/html; charset=gb2312");
session_start(); //初始化session变量
$user=$_POST['name']; //接收表单提交的用户名
$pswd=$_POST['pwd']; //接收表单提交的密码
//$pswd=md5($_POST['pwd']); //md5和select password结果不一致
class chkinput  //定义类
{
  var $name;
  var $pwd;
  function chkinput($x,$y) //定义一个方法
  {
    $this->name=$x; //将管理员名称传给类对象$this->name
    $this->pwd=$y; //将管理员密码传给类对象$this->pwd
  }
  function checkinput()
  {
    include("conn.php"); //连接数据库文件
	$sql_pwd=mysql_query("select password('".$this->pwd."')",$conn);
	$sql_pwd_code=mysql_result($sql_pwd,0);
	
    $sql=mysql_query("select user,password from user where user='".$this->name."' and password='".$sql_pwd_code."'",$conn);
    $info=mysql_fetch_array($sql); //检索管理员名称和密码是否正确
    if($info==false) //如果管理员名称或密码不正确,则弹出相关提示信息
    {
      header("location:login.php?error=1");
      exit;
    }
    else //如果管理员名称或密码正确,则直接跳转到登陆成功后界面
    {
      header("location:login.php?error=2");
      $_SESSION['admin_name']=$info['username']; //将管理员名称存到$_SESSION[admin_name]变量中
      $_SESSION['pwd']=$info['password']; 将管理员名称存到$_SESSION[pwd]变量中
    }
  }
}
$obj=new chkinput(trim($user),trim($pswd)); //创建对象
$obj->checkinput(); //调用类
?>

实现了对数据库的查询,看是否正确,并设置输入对与错时定向到哪个状态。

这个php文件调用了conn.php,下面是代码:

<?php
header("Content-type: text/html; charset=gb2312");
$conn = mysql_connect("localhost","root","******");
if(!$conn)
{
  die("连接数据库失败".mysql_error());
}
mysql_select_db("mysql") or die("数据库选择失败".mysql_error());
mysql_query("set names 'gb2312'");
?>

注意里面把密码修改为你的mysql的root的密码。

看看效果:

输入正确时:

 

错误时:

 基本功能已实现。

 

举报

相关推荐

0 条评论