检查具有相同名称列的两个表中的重复项

时间:2016-06-21 22:06:50

标签: php mysql

我是一名有限编程语言的业余爱好者,请帮忙。 我有以下代码:

try
  {
     $stmt = $DB_con->prepare("SELECT user_email FROM m_users WHERE user_email=:umail");
     $stmt->execute(array(':umail'=>$umail));
     $row=$stmt->fetch(PDO::FETCH_ASSOC);

     if($row['user_email']==$umail) {
        $error[] = "Sorry but someone has already registered with this email address !";
     }
     else
     {
        if($user->register($umail,$ucountry,$uip)) 
        {
            $user->redirect('m_c.php');
        }
     }
 }
 catch(PDOException $e)
 {
    echo $e->getMessage();
 }

此代码 - 实际上 - 只在一个名为m_users的表中查找重复的电子邮件,如果找到,则会发出通知。

我想要的是它在名为f_users附加表中查找并检查AS WELL,该表具有完全相同的列结构。 我尝试了不同的技巧无济于事。 非常感谢提前。

3 个答案:

答案 0 :(得分:0)

我的PHP非常生疏,但您可以运行另一个查询并在条件中检查:

$stmt = $DB_con->prepare("SELECT user_email FROM m_users WHERE user_email=:umail");
$stmt->execute(array(':umail'=>$umail));
$row=$stmt->fetch(PDO::FETCH_ASSOC);

$stmt = $DB_con->prepare("SELECT user_email FROM f_users WHERE user_email=:umail");
$stmt->execute(array(':umail'=>$umail));
$row_2=$stmt->fetch(PDO::FETCH_ASSOC);

if($row['user_email']==$umail or $row_2['user_email']=$umail) {
   $error[] = "Sorry but someone has already registered with this email address !";
}

答案 1 :(得分:0)

您是否可以更改SQL查询,以便在一个查询中查找两个表中的电子邮件地址?

SELECT user_email FROM m_users WHERE user_email=:umail 
UNION 
SELECT user_email FROM f_users WHERE user_email=:umail

答案 2 :(得分:0)

对于我所阅读的内容,我只是猜测,你有一个男性用户表和另一个女性用户表,你可以将两个表合并到另一个表中并添加性别列。现在有很多方法来解决你的问题,但我建议这个,它添加另一个else语句并运行相同的查询,但更改表名。

<?php 
try{
    $stmt = $DB_con->prepare("SELECT user_email
        FROM m_users 
        WHERE user_email=:umail");
    $stmt->execute(array(':umail'=>$umail));
    $row=$stmt->fetch(PDO::FETCH_ASSOC);

    if($row['user_email']==$umail) {
        $error[] = "Sorry but someone has already registered with this  email address !";
    }else{
        $stmt = $DB_con->prepare("SELECT user_email
        FROM f_users 
        WHERE user_email=:umail");
        $stmt->execute(array(':umail'=>$umail));
        $row=$stmt->fetch(PDO::FETCH_ASSOC);
        if($row['user_email']==$umail) {
            $error[] = "Sorry but someone has already registered with this  email address !";
        }
    }else{
        if($user->register($umail,$ucountry,$uip)){
                $user->redirect('m_c.php');
        }
    }
 }catch(PDOException $e){
        echo $e->getMessage();
     }

?>