【问题标题】:Fails to catch duplicate无法捕获重复项
【发布时间】:2013-02-17 23:58:20
【问题描述】:

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

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

【问题讨论】:

  • 请提供一些信息或数据库结构示例。谢谢!
  • 用于电子邮件检查的 if-else 构造错误,回显不会停止脚本
  • 您是否对输入进行了清理(即,在所有字符串输入上运行 mysql_real_escape_string())?我怀疑问题是否存在,但它会帮助您避免其他问题(如 SQL 注入)。
  • 正如 Sam 指出的那样,您的 if/else 代码中存在错误。你的是 if () { }} else { },什么时候应该是 if () { } else { }。
  • 在 else 之前有两个 } }?

标签: php mysql duplicates populate


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-03-21
      • 2014-09-22
      • 2019-03-18
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 2019-10-08
      • 1970-01-01
      相关资源
      最近更新 更多