如何检测已在数据库中使用的用户名

时间:2013-08-26 12:41:30

标签: php

<?php

if(isset($_POST["Add"]))    
{

$name=$_POST["Emp_Username"];
$pass=$_POST["Emp_Password"];
$fname=$_POST["Emp_Fname"];
$lname=$_POST["Emp_Lname"];
$hph=$_POST["ContactNo_Home"];
$hp=$_POST["ContactNo_HP"];
$mail=$_POST["Emp_Email"];
$add=$_POST["Emp_Address"];
$age=$_POST["Emp_Age"];
$pos=$_POST["Position"];
$dept=$_POST["Dept_ID"];

mysql_query("
    insert into employee(Dept_ID, Emp_Address, Emp_Age, 
    Position, >Emp_Username, Emp_Password, Emp_Fname, Emp_Lname, 
    ContactNo_Home, ContactNo_HP, Emp_Email) 
    >values('$dept','$add','$age','$pos','$name','$pass','$fname',
    '$lname','$hph','$hp','$mail'>)
   ");

?>    

<script type="text/javascript">
alert("Record saved.");    
</script> 

<?php } ?>

4 个答案:

答案 0 :(得分:2)

在用户名字段上创建一个唯一键,然后检测错误号1062:

if (mysql_errno() == 1062) {
    print 'username taken!';
}

答案 1 :(得分:1)

一个简单的SELECT查询就足够了:

SELECT COUNT(employee.Emp_Username) AS num 
FROM employee 
WHERE Emp_Username = 'USERNAME';

答案 2 :(得分:0)

我希望这能帮到你,

$query=mysql_query("select * from employee where Emp_Username=$name");
    $row=mysql_num_rows($query);
    if($row>0){
        echo 'user exist';
    }else{
        echo 'User not exist';
    }

答案 3 :(得分:0)

也许您应该在提交表单

之前使用ajax验证字段“user”
$name = $_POST["Emp_Username"];
$results = mysqli_query($connecDB,"SELECT * FROM employee WHERE Emp_Username='$name'");
$name_exist = mysqli_num_rows($results);

if($username_exist) {
    echo 'busy';
}else{
    echo 'free';
}