1

我正在尝试制作一个脚本,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>.";
}

该脚本在填充数据库时运行良好,但是如果电子邮件地址已存在于数据库中,它就无法捕获。谁能发现问题?

4

2 回答 2

4

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

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

同样如注释中所述,您的代码易受SQL Injection. 我建议你使用prepared statements.

于 2013-03-03T23:53:02.917 回答
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>.";
    }
于 2013-03-03T23:54:35.923 回答