dongwu9972
2013-03-03 23:48 阅读 53
已采纳

无法捕捉重复

I'm trying to make a script that 1) Checks if an entry with the given email address already exists in the DB, and if not 2) Populates the DB with a new entry.

This is the code I currently have:

$result = mysql_query("SELECT * FROM cbsclassy WHERE email = '$email' LIMIT 1");
$num_rows = mysql_num_rows($result);

if ($num_rows > 0) { echo "It seems that you're already participating. It is
only allowed to make one entry into the competition. <a href=index.html>Click to
return to the previous page</a>.";  
}

else { $sql="INSERT INTO cbsclassy (name, email, answer) VALUES
        ('$name','$email','$answer')";

        if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error());
        }

        echo "You're now participating in the contest. The winners will be
        notified        directly via email. Good luck! <a     href=index.html>Click
        to return to the previous page</a>.";
}

The script is working fine when it comes to populating the DB, however it doesn't catch if the email address already exists in the DB. Can anyone spot the problem?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dopod0901 dopod0901 2013-03-03 23:53

    You have two }'s before the else so it gets triggered every time.

    It'd be more efficient to set a UNIQUE KEY on the email field and then check the amount of affected rows when inserting to know if it existed or not.

    Also as noted in the comments your code is vulnerable to SQL Injection. I recommend you use prepared statements.

    点赞 评论 复制链接分享
  • douzhangjian1505 douzhangjian1505 2013-03-03 23:54

    Correct the if/else construct

    if ($num_rows > 0) { echo "It seems that you're already participating. It is
    only allowed to make one entry into the competition. <a href=index.html>Click to
    return to the previous page</a>.";  
         } //here remove a }
    
      else { $sql="INSERT INTO cbsclassy (name, email, answer) VALUES
             ('$name','$email','$answer')";
                   if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error());
                 }
               //and also here   
        echo "You're now participating in the contest. The winners will be
           notified        directly via email. Good luck! <a     href=index.html>Click
            to return to the previous page</a>.";
        }
    
    点赞 评论 复制链接分享

相关推荐