I’m creating a comment system for my website. Right now its just a basic comment system. But I would like my users to have the option to get emails when there is a new comment.
To do this I first made another table called: ’email_notifications’
and then I just put the email in there. The reason im doing this in another table. Was to prevent getting emails more than once.
For example.
I post a comment that says: ‘Cool Site’,
then I post another later saying: ‘Cool!’,
but then when someone comments after mine, I get an email twice because I posted twice.
I tryed prevented this to happen using:
if(mysql_num_rows(mysql_query("SELECT * FROM email_notifications WHERE email='$email'") or die(mysql_error())) == 0) {
mysql_query("INSERT INTO email_notifications (email) VALUES ('$email')") or die(mysql_error());
}
And Im kinda knew to PHP and mysql…so Im not sure whats wrong. This is suppose to not send the mysql_query if the email is already in the table. But for some reason it keeps on adding it in the table. And when my email is in there twice then, I get the email twice.
Thanks in Advance!
If you notice sites like facebook generalize the notification system by sending a generic message “you have notifications pending” which means they run a cron and check true or false if you do have a pending message then send you a link to the list. You can make it more robust if you want, but the general point is to run a cron that checks instead of doing it on a per notification basis.
The way we do it is log the notification status in a relational table that points to user_id, action (in this case a notification) post_id, datetime, and status (pending, complete, etc) then use that info to send a basic message telling the subscriber they have new comments or something. If they only have one, we print it out in the email by selecting count() after verifying there are notifications.
This running on a cron processes things in the background where efficiency and complexity can be managed silently, transparent to the user. It’s too complex to list out entirely, but the point is manageable for a competent programmer.
Look into REPLACE INTO for mysql. We use that in the notifications tables to replace the last entry, resetting the status to pending. Then the cron selects where status is pending… see the point? Hope it helps.