仅检查电子邮件,而不是用户名

时间:2016-04-05 09:15:24

标签: php mysql

我有这个代码来检查数据库中的电子邮件可用性,但它只检查电子邮件而不是用户名。我想检查电子邮件和用户名,我试图通过下面的代码检查它们但它不起作用。

代码有什么问题?

<?php
require_once './config.php';
if (isset($_POST["sub"])) {
    $fname = ($_POST["fname"]);
    $lname = ($_POST["lname"]);
    $name = ($_POST["username"]);
    $pass = ($_POST["password"]);
    $email = ($_POST["email"]);
    $sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id ";
    try {
        $stmt = $DB->prepare($sql);
        $stmt->bindValue(":email_id", $email);
        $stmt->bindValue(":username_id", $name);
        $stmt->execute();
        $result = $stmt->fetchAll();
        if ($result[0]["count"] > 0) {
            echo "<div style='color:red;' class='errorbox'>Incorrect Username or Password</div><br>";
        }  else {
            $sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
        }
    }
}
?>

4 个答案:

答案 0 :(得分:2)

您的SQL语句有问题,您正在检查电子邮件和用户名是否在一起尝试更改您的语句

$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id "

$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id "

只要用户名或电子邮件显示证明它们不是唯一的

,这就会强制返回1

答案 1 :(得分:0)

印刷错误。这行应该被替换:

$stmt->bindValue(":username_id", $email);

应替换为:

$stmt->bindValue(":username_id", $name);

答案 2 :(得分:0)

你正在使用和条件。如果您使用或条件意味着它会没事。

$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";

答案 3 :(得分:0)

也许你在这里有错误:

$stmt->bindValue(":email_id", $email); //ok 
$stmt->bindValue(":username_id", $email); //you bind with $email again .. is it normal ?

You should validate your $_POST datas with !empty i.e.:
if(!empty($_POST["email"]) $email = $_POST["email"]) ... because with your actual code you could make sql queries with empty $email = null