Reputation: 6062
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
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
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