当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP验证用户名重复注册【新手】

PHP验证用户名重复注册【新手】

2018年12月19日  | 移动技术网IT编程  | 我要评论

本小结利用最简单的方式通过php验证表单递交内容(用户名)是否存在于数据表中。如果存在了,则显示已经被注册,如果不存在则可以正常注册。

详细代码如下:

步骤省略数据库、数据表的建立。

前端递交页面代码如下:

register.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>用户名重复验证</title>
  </head>
  <body>
    <form action="register.php" method="post">
      <!-- action指向递交页面 method为递交方法 -->

      <label>用户名:<input type="text" name="username"/></label> <br />
      <button type="submit">注册</button>
      <!-- 这里的注册按钮使用<input type="submit">标签和<button>标签都可以 -->
    </form>
  </body>
</html>

完成前端注册页之后,现在开始写php接受页:

register.php

<?php
include('conn.php');
//php链接数据库代码,在这里我用创建的单独连接页'conn.php',代码附下文

mysql_query("set character set 'utf8'");//读库 
mysql_query("set names 'utf8'");//写库 
//这两行代码能够保证从网页递交到数据库的内容显示中文格式不乱码,如果是注册的话可以只写'写库'一段

//查询语句,帮助协助查询当前注册用户名是否存在于数据库当中
$sql = "select * from t_user where username='$_post[username]'";
//第一个'username'为数据库内已存在的username值,将其与第二个'post'方法传递过来的username值做对比

$rs = mysql_query($sql);
if(mysql_num_rows($rs)>0)//如果数据库内存在相同用户名,则'$rs'接收到的变量为'true'所以大于1为真,则返回'用户名已存在'
{
    echo "用户名已存在,请重新注册!";
    echo "<a href=register.php>[注册]</a>";
} else //否则可以成功注册递交
{
   $sql="insert into t_hospital (username) values ('$_post[username]')";
if (!mysql_query($sql))
    {
      die('error: ' . mysql_error());
    }
echo "<span>注册成功!</span>";//显示注册成功信息
header("refresh:1;url=login.php");//一秒后刷新进入登录页
}
?>

php链接数据库页面:

conn.php:

<?php
 $conn = mysql_connect("127.0.0.1","root","") or die("数据库链接错误".mysql_error());
 mysql_select_db("db",$conn) or die("数据库访问错误".mysql_error());
 mysql_query("set names gb2312");
?>

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网