如何在单个查询中获得两个单独的错误结果

时间:2017-04-08 20:14:50

标签: php mysql pdo

尝试使用PDO制作基本用户注册脚本,当用户和电子邮件存在时,我收到单个错误消息(用户或电子邮件已存在),我试图获取用户和电子邮件错误的单独输出。关于这个脚本的任何其他建议非常感谢

if(isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
//Validating ???


$statement  = $conn->prepare("SELECT COUNT(*) AS count FROM users 
    WHERE username = :username AND email = :email");
$statement->bindParam(':username', $username);
$statement->bindParam(':email', $email);
$statement->execute(array(':username' => $username, ':email' => $email));

    while ($row = $statement ->fetch(PDO::FETCH_ASSOC)) {
      $result = $row["count"];
        }
        if ($result > 0) {
            echo "That usernam or email is already taken";

            }
        else {
            $sql = ("INSERT INTO users(username, email, password) VALUES(?, ?, ?)");
            $statement = $conn->prepare($sql);
            $statement->bindValue(":username", $username, PDO::PARAM_STR);
            $statement->bindValue(":password", $password, PDO::PARAM_STR);
            $statement->bindValue(":email", $email, PDO::PARAM_STR);
            $statement->execute(array("$username", "$email", "$password"));
            echo "New record created successfully";
            }
}

3 个答案:

答案 0 :(得分:2)

我可能会这样做:

SELECT
   COUNT(IF (username IS NOT NULL AND username != '', 1, NULL)) AS username_taken
 , COUNT(IF (email IS NOT NULL AND email != '', 1, NULL)) AS email_taken
FROM users 
WHERE LOWER(username) = LOWER(TRIM(:username))
OR LOWER(email) = LOWER(TRIM(:email))

注意,我在这里使用COUNT()的原因是,如果有两个结果行,则会聚合。 COUNT()会忽略NULL,因此会将两行压缩为一行并返回10(来自COUNT()),或者只提供1对于两列,如果它是同一行。

另外,正如@Fred -ii-所指出的那样,你为之后正在进行的绑定类型调用了错误的PDO方法。所以:

$sql = "
INSERT INTO users (
   username, email, password
) VALUES (
   TRIM(:username), TRIM(:email), :password
)
";

$statement = $conn->prepare($sql);

$statement->bindParam(":username", $username, PDO::PARAM_STR);
$statement->bindParam(":password", $password, PDO::PARAM_STR);
$statement->bindParam(":email", $email, PDO::PARAM_STR);

答案 1 :(得分:0)

$username = $statement->fetchColumn();
$email = $statement->fetchColumn(1);

if ($username != null) {
    echo "Username already taken";
}
elseif ($email != null) {
    echo "Email already taken";
}
else{
    //Insert entry into DB
}

OR

if ($row["username"] != null) {
   echo "Username already taken";
}
elseif ($row["email"] != null) {
    echo "Email already taken";
}
else{
    //Insert entry into DB
}

此外,您的查询需要更改为:

SELECT COUNT(*) AS count FROM users WHERE username = :username OR email = :email

因为使用您当前的查询,您无法同时检查用户名和电子邮件地址。

答案 2 :(得分:-2)

为了获得不同的错误消息,必须分离查询。

  1. 检查用户名(如果找到,抛出错误)
  2. 如果找不到,请检查电子邮件(如果找到,抛出错误)
  3. 如果未找到,请插入用户数据