Shawn31313
Shawn31313

Reputation: 6062

Why is my PHP if statement not working correctly?

I'm creating a comment system and when a new comment comes I will email them.

I created a table in phpMyAdmin called email_notifications.

The problem is with this code:

if(mysql_num_rows(mysql_query("SELECT * FROM email_notifications WHERE email='$email'") or die(mysql_error())) <= 1) {
    mysql_query("INSERT INTO email_notifications (email) VALUES ('$email')");
    echo mysql_num_rows(mysql_query("SELECT * FROM email_notifications WHERE email='$email'"));
} 
else{
    die('EMAIL!');
}

That is suppose to prevent more than one of the same email to be in that table. And right now mysql_num_rows says that there are 7 rows.

So the statment now says:

if(7 <= 1) {
    mysql_query("INSERT INTO email_notifications (email) VALUES ('$email')");
    echo mysql_num_rows(mysql_query("SELECT * FROM email_notifications WHERE email='$email'"));
}
else{
    die('Can\'t post this email! Sorry.');
}

The problem is that it's still inserting the email address into the table but it shouldn't. It should be returning Can't post this email! Sorry.

This is probable the weirdest problem I've faced and I can't figure it out :(

Please help, thanks in advance.

Upvotes: 2

Views: 137

Answers (2)

max_
max_

Reputation: 24521

Evidently, the value of mysql_num_rows(mysql_query("SELECT * FROM email_notifications WHERE email='$email'") or die(mysql_error()) is not equal to 7, and is therefore, less than or equal to 1. This is the reason why your if statement is not running as expected.

Also, please format your code a bit better:

$query = mysql_query("SELECT * FROM email_notifications WHERE email='$email'") or die(mysql_error());

$numberOfRows = mysql_num_rows($query);

echo $numberOfRows; //check the number of rows.

if($numberOfRows <= 1) {
    mysql_query("INSERT INTO email_notifications (email) VALUES ('$email')");
    $query_ = mysql_query("SELECT * FROM email_notifications WHERE email='$email'");
    var_dump(mysql_num_rows($query_));
} 
else{
    die('EMAIL!');
}

Upvotes: 6

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

What's wrong with just adding a key?

ALTER TABLE email_notifications ADD UNIQUE email (email)

Never have to worry about duplicates again.

Upvotes: 6

Related Questions