想知道电子​​邮件或用户名是否已经存在[mysql,php]

时间:2014-11-09 16:14:19

标签: php mysql database

我想如果用户名或电子邮件已存在于数据库

$prep_stmt = "SELECT `id` FROM `members` WHERE `email` = ? LIMIT 1";
    $stmt = $this->db->prepare($prep_stmt);

    if ($stmt) {
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->store_result();

            if ($stmt->num_rows == 1) {
                return "A user with this email address already exists";
            }
     } else {
         return "Database error";
     }

现在我可以为用户名做同样的事情,但我想知道是否有办法用mysql做到这一点

我试着这样做......

SELECT `id` FROM `members` WHERE `email` = "user@user.com" OR `username` = "testuser" LIMIT 1

但如果电子邮件和用户名相同,则显示没有LIMIT TAG 2 ID,我不知道哪个用于电子邮件或用户名,如果我使用LIMIT TAG拨打电话,则会显示一个结果我仍然不知道是用户名还是电子邮件是相同的

2 个答案:

答案 0 :(得分:2)

你可以使用:

SELECT `id`, 
       IF(`email` = "user@user.com",1,0) as foundMail,
       IF`username` = "testuser"   ,1,0) as foundUser
FROM `members` 
WHERE `email` = "user@user.com" 
  OR `username` = "testuser"
如果邮件匹配,

foundMail将为1,如果用户匹配,则foundUser将为1

问候

答案 1 :(得分:0)

试试这个:

<?php
// you should use * for all columns selected instead of id
$stmt="SELECT * FROM members WHERE email=:txtemail LIMIT 1";
$calldata = $db->prepare ($stmt);
$calldata->bindParam(':txtemail', $txtemail, PDO::PARAM_STR,27);
$calldata->execute();
$result = $calldata->fetchColumn();     
if (htmlspecialchars($result) == false){
    //some script if not found
    }
else{
    //some script if found or exists
}
?>