View Full Version : if/else not working with mySQL command?

07-15-2007, 08:19 AM
I'm trying to set up a basic email list, starting with the following:

if($_POST['gf_email_signup']=='Yes') {
$sql = "SELECT email from e_mailing_list where e_mailing_list.email = '$_POST[gf_email_signup]'";
$result = mysql_query($sql, $conn) or die(mysql_error());
if(mysql_num_rows($result) != 0) {
$email_signup_notice = '(Your email address was already on our mailing list)';
} else {
$sql = "INSERT INTO e_mailing_list values ('','$date','$_POST[gf_name_first]','$_POST[gf_name_last]','$_POST[gf_email]')";
$result = mysql_query($sql, $conn) or die(mysql_error());
$email_signup_notice = '(Your email address was successfully added to our mailing list)';
The problem is, after an email address is added, if that address is attempted to be added again (i.e. test@email.com is already in the list but someone tries to add it again), the if/else clause does not work. It skips to the else section and then returns as mySQL error because the email field is set as unique. Am I missing something as to why the if/else is not working to detect a duplicate address? Am I going about this the wrong way?

My apologies if this belongs in the mySQL forum; I am new to mySQL but this seemed to me to be a php problem... but again, I'm new to mySQL so I could be wrong, and maybe the solution is quite obvious to a more seasoned coder...

Thanks in advance.

07-15-2007, 10:26 AM
try echoing out the result of mysql_num_rows - its the only condition in your if so thats the first place to start

07-15-2007, 03:10 PM
I would suggest you echo $sql to make sure it contains what you expect and/or proof read your code (you will find that your query is referencing the $_POST variable - gf_email_signup, which apparently contains "Yes" at the time of the query, when it should be using the $_POST variable - gf_email.)

07-15-2007, 05:11 PM
Thanks! I echoed mysql_num_rows and it was as it should be. Then, of course, I saw that in the query I had mixed up gf_email_signup with gf_email - good catch (obviously nobody's email address was going to equal 'Yes', as the query was erroneously set up to check)!!! And of course, I feel embarassed that it was something so simple, but thanks to both of you for your help. Sometimes it just takes an outside eye.