Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my PHP if statement not working correctly?

Tags:

php

mysql

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.

like image 575
Shawn31313 Avatar asked Nov 23 '25 23:11

Shawn31313


1 Answers

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!');
}
like image 89
max_ Avatar answered Nov 25 '25 16:11

max_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!