使用EXISTS检查重复的用户名

时间:2017-03-22 03:29:55

标签: php sql pdo

我一直在检查检查重复用户名的最佳方法我看到有人说EXISTS性能更好,这个公式好吗?还是有更好的? IF EXISTSSELECT EXISTS以及WHEN EXISTS之间有什么区别?是否可以在代码中合并电子邮件并同时检查电子邮件和用户名?或者将两个quires分开是否更好?

$username = $_POST['username'];
    $stmt = $conn->prepare("SELECT EXISTS (SELECT username FROM users WHERE username = :username)");
    $stmt->execute([':username' => $username]);
    if ($stmt->fetchColumn() > 0) {
        echo "Username is already taken.";
    }

2 个答案:

答案 0 :(得分:1)

如果为true则返回bit,然后返回1,否则返回False 0

    SELECT CASE WHEN EXISTS (
        SELECT username FROM users WHERE username = :username
    )
    THEN CAST(1 AS BIT)
    ELSE CAST(0 AS BIT)
    END AS result

答案 1 :(得分:0)

您可以将用户名或电子邮件设置为唯一键。然后使用try .. catch

try {
  // do your insert query. If it fails to insert, it will throw error message
  // Also need to turn on error exception mode for PDO attribute
} catch (PDOException $e) {
  echo $e->getMessage();
}

您可以使用SQL:

  • SQL COUNT

    $ stmt = $ conn-> prepare(' SELECT COUNT(用户名)AS total FROM users WHERE username =:username');

    //或$ stmt = $ conn->准备(' SELECT COUNT(用户名)AS用户总数= username =:username AND email =:email');

    $ stmt-> bindParam(':username',$ username); $ stmt-> bindParam(':email',$ email); $ stmt->执行(); $ row = $ stmt-> fetch(PDO :: FETCH_OBJ); if($ row-> total> 0){    echo'用户名/电子邮件已经拍摄。&#39 ;; }

    [1]:http://php.net/manual/en/pdo.setattribute.php