表单(表名:res.html)
<form action="res.php" method="get">
id:<input type="text" name="userId"><br>
name:<input type="text" name="userName"><br>
<input type="submit" value="注册">
</form>
表单对应的php(res.php)
<?php
header("Content-type:text/html;charset=utf-8");
$id=$GET["userId"];
$name=$GET["userName"];
$conn=mysql_connect("localhost","root","root");
//localhost指的是域名,账号和密码是root;
//是phpstudy里默认的
mysql_select_db("在自己的phpstudy创建数据库");
//实际是查找
$result=mysql_query("select*from student(在自己的数据库中
创建表) where stu_id=$id AND stu_name='$name'".$conn)
if(mysql_num_rows($result)==1){
echo "用户已经存在"
//数据库表中有这个id、name则注册不了
}else{
echo "用户可以注册";
mysql_query("insert into student values ($id,"$name",
18,"1988-5-16")",$conn);
//能注册后顺便把注册信息追加到信息库
}
mysql_close($conn)
//这个案例中id或者name只要数据库中有任一一个个,都显示
可以注册
?>
用ajax验证用户名是否存在
<body>
<input type="text"><span></span>
</body>
<script>
let oinput=document.querySelector("input");
oinput.onblur=function(){
let xhr=new XHMLttpRequest();
xhr.open("post",ajax.php,true);
xhr.setRequestHeader("Content-Type","application/
x-www-form-urlencoded");
xhr.send("userName="+this.value);
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
fun(xhr.responseText)
}
}
}
function fun(resText){
let span=document.querySelector("span");
if(resText=="1"){
span.innerHTML="用户名存在"
}else if(resText=="0"){
span.innerHtml="可以注册"}
}
</script>
Ajax.php
<?php
header("Content-type:text/html;charset=utf-8");
$userName=$_POST["userName"];
$conn=mysql_connect("localhost","root","root");
mysql_select_db("新数据库");
$result=mysql_query("select * from student where
stu_name='$userName'",$conn);
if(mysql_num_rows($result)==1){
echo "1";
}else{
echo"0";
}
?>
|