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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条