ajax php 验证注册用户名是否存在

时间:2023-12-19 14:19:32

1.在"test"数据库中,建立一张名为"user"的表.

sql语句:

 create table `user`(
`id` int(5) not null auto_increment primary key,
`username` varchar(10) not null,
`password` varchar(12) not null,
`email` varchar(50) not null
);

2.新建register.html文件

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$(".register input:first").blur(function(){
$.ajax({
type: "post",
url: "register.php",
data: "username=" + $(".register input:first").val(),
success: function(msg) {
$("#userinfo").html(msg);
}
});
});
});
</script>
<style type="text/css">
*{margin:0px;padding:0px;}
.register{width:550px;height:250px;padding:25px;margin:200px auto;border:2px solid #7aba5f;}
.display {width:350px;height:60px;float:left;margin-right:20px;}
.reginfo {width:150px;height:60px;float:left;margin-right:20px;color:#999999;font-size:13px;line-height:30px;}
.register input{width:300px;height:30px;border:1px solid #7aba5f;}
.register input.submit{width:100px;height:40px;color:white;font-size:16px;background:#7aba5f;border:none;margin-top:30px;margin-left:150px;}
</style>
</head>
<body>
<div class="register">
<div class="display">
账号:<input type="text" name="username" />
</div>
<div class="reginfo" id="userinfo">
请输入您的账号.
</div>
<div class="display">
密码:<input type="password" name="password" />
</div>
<div class="reginfo">
请输入您的密码.
</div>
<div class="display">
邮箱:<input type="text" name="email" />
</div>
<div class="reginfo">
请输入您的邮箱.
</div>
<input type="submit" name="submit" size="30" value="注册" class="submit" />
</div>
</body>
</html>

3.新建register.php文件

 <?php
$username = $_POST['username'];
if (!empty($username)) {
mysql_connect("127.0.0.1", "root", "");
mysql_select_db("test");
$sql = "SELECT `username` FROM `user` WHERE `username` = '$username' LIMIT 1";
$re = mysql_query($sql);
while ($row = mysql_fetch_assoc($re)) {
$temp = $row;
}
if (empty($temp)) {
echo "<font color=green style='font-size:16px;'><b>恭喜,可以注册!</b></font>";
} else {
echo "<font color=red style='font-size:16px;'><b>抱歉,无法注册!</b></font>";
}
} else {
echo "<font color=red style='font-size:16px;'><b>请输入您的账号.</b></font>";
} ?>