检查现有用户名无效

时间:2016-02-15 07:52:14

标签: php mysql

我迷失在这里。请帮助。 tqvm。注册没有问题,但即使用户名已经存在,它仍然会添加。 tq再次。

1.register.php

<?php 

require "conn.php";

$name = "123";
$username = "bob";
$password = "!23";
$role = "123";

$checkdata=" SELECT username FROM employee_data WHERE username='$username'  ";

$query=mysql_query($checkdata);

if(mysql_num_rows($query)>0)
{
echo "User Name Already Exist";
}

else{
$mysql_qry = "insert into  employee_data (name, username, password, role)   values ('$name', '$username', '$password', '$role')";
if($conn->query($mysql_qry) === TRUE){

    echo "Success Registration";
}
else {
    echo "Fail Registration";
}
}


$conn->close();

?>

2 个答案:

答案 0 :(得分:0)

我不知道$ conn实例。我没有创建,你在哪里创建了实例。所以我删除了$ conn。试试这个,     

require "conn.php";
$name = "123";
$username = "bob";
$password = "!23";
$role = "123";

$checkdata="SELECT username 
              FROM employee_data 
             WHERE username='$username'  ";
$query = mysql_query($checkdata);
if(mysql_num_rows($query)>0) {
    echo "User Name Already Exist";
} else {
    $mysql_qry = "insert into  employee_data (name, username, password, role)   values ('$name', '$username', '$password', '$role')";
    $store = mysql_query($mysql_qry);
    if($store){
        echo "Success Registration";
    } else {
        echo "Fail Registration";
    }
}

?>

使用PDO

<?php 

$host = "";     # Host name
$dbName = "";   # Database name
$userName = ""; # user name to thye host
$password = ""  # password to the host

$pdoHandler = 'mysql:host='.$host.';dbname='.$dbName.';';
$pdo = new PDO($pdoHandler, $userName, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$name = "123";
$username = "bob";
$password = "!23";
$role = "123";

try {

    $checkdata="SELECT username 
                  FROM employee_data 
                 WHERE username=?";
    $query = $pdo->prepare($checkdata);
    $query->execute(array($username));
    $userExist = $query->fetch(PDO::FETCH_ASSOC);

    if($userExist) {
        echo "User Name Already Exist";
    } else {
        $mysql_qry = "INSERT INTO employee_data(name, username, password, role)
                             VALUES (?, ?, ?, ?)";
        $store = $pdo->prepare($mysql_qry);
        $store->execute(array($name, $username, $password, $role));
        if($store){
            echo "Success Registration";
        } else {
            echo "Fail Registration";
        }
    }
} catch (PDOException $e) {
    print "SQL Error: ".$e->getMessage();
}

?>

答案 1 :(得分:0)

<?php

require "connection.php";

$name = "123";
$username = "foo";
$password = "!23";
$role = "123";

$checkdata="SELECT username FROM employee_data WHERE username='{$username}'";

$query=mysql_query($checkdata) or die(mysql_error());

if(mysql_num_rows($query)>0) {
    echo "User Name Already Exist";
} else {
    echo "ok"; // registration code here
}
?>

尝试这个