无法捕捉重复

时间:2013-03-03 23:48:20

标签: php mysql duplicates populate

我正在尝试创建一个脚本1)检查数据库中是否已存在具有给定电子邮件地址的条目,如果不存在,则2)使用新条目填充数据库。

这是我目前的代码:

$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>.";
}

在填充数据库时,脚本工作正常,但如果数据库中已存在电子邮件地址,则无法捕获。有谁能发现问题?

2 个答案:

答案 0 :(得分:4)

你在else之前有两个},所以每次都会触发它。

在电子邮件字段中设置UNIQUE KEY然后在插入时检查affected rows的数量以确定它是否存在会更有效。

同样如评论中所述,您的代码容易受到SQL Injection的攻击。我建议你使用prepared statements

答案 1 :(得分:0)

更正if / else构造

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>.";
    }