I am developing a notification system in PHP, MySql, jquery ajax on a website that i am working on. I have a post which you follow if you comment on it. My problem is that i am stuck i don't know how can i send notification to all the users following the post. I did successfully send notification to the creator or the post though.
in the code i will be showing the query that enters a notification into notifications table, i will post the notifications_table structure and discussion_followers table which include the users following a post
here is the query that enters the notification into the notifications_table
// the board user_id is not the same as the logged in user which means the logged in user is not commenting on his post
// which means we insert notification in table
$query_not = "INSERT INTO notifications ( ";
$query_not .= "from_user, to_user, post_type, post_id, type, comment_id, notification_timestamp";
$query_not .= ") VALUES (";
$query_not .= " $user_id, $discussion_user_id_check, 'discussion', $discussion_id, 'comment', $fetched_comment_id, $discussion_comment_timestamp";
$query_not .= ")";
$result_not = mysqli_query($connection, $query_not);
so what i already achieved is : a user which is not the logged in user comments on a discussion post if he hasn't already followed the post he will will follow by entering his id with the post id into the following table, a new notification is inserted into the notifications_table. The user who created the post will receive this notification. What i want to achieve more is send notifications to all following this post that a new comment has been entered.
The notifications table structure is as follow:
notification_id, from_user, to_user, post_type, post_id, type, comment_id, reply_id, notification_timestamp, viewed
example of notification:
121, 20, 30, discussion, 31, comment, 39, 0, 1534184319, 0
discussions_followers table which follow the discussion post structure is :
follow_id, user_id, discussion_id
Honestly if i want to do what you want, i do not create my data structure like that to fill the purpose. but what ever, you can do a query:
select from_user from notifications where post_id={discussion_id} group by from_user;
then all ids fetched are users you want to push notification from new user. (you can skip $from_user==$user_id). lets say you have $result, then (simple code):
for($i=0, $i<count($result); $i++){
insert into notifications (from_user, to_user) values ($user_id, $result[$i]
['from_user'])
}
what i prefer:
for system like push notification. i always prefer to implement whole system as microservice and outside my project. (just you know not related). but what i do, i would use one of those message queue systems and not store such data in database FOR READ. your table is more like a log table which you can log you notification and write what ever you want to it for further process. but for read from it just to know who should push who, its not efficient. so have table post with 1 unique id and users id involved with that post. on each comment create queue with id "push-$id" and push comment and user id to it one by one. background manager of queues will know how to handle queues with id "push-*". creating queue may be a problem here so you can create empty one on each post created. (its not doing anything cause by that you just create pointer nothing else).
Related
Just a question about what the best way is to send a message to a group (Like whatsapp group messaging).
I save the members per group into a separate database table and once a user sends a message to the group it retrieves the users from this table. I'm a bit stuck on part two:
As I see it there would be three methods.
Insert the message into a database for the entire group. Send the message back to the different users based on groups they are member of.
Insert the message in the database per user of the group. So loop the members and insert for every member. This has the advantage over the first method that downloaded, read and deleted status can be tracked.
Create a table for messages and one for the message-recipient link. But I'm not really sure how a would query in the most optimum way as to retrieve all the data (downloaded, read, etc) for a group of users. Is that possible in a single query?
Would anyone know what the best method would be? I can imagine that method 2 will fill up a database pretty fast, but method 1 doesn't have the ability of tracking status for a message.
At the moment I am using method 1, but I run into the problem that when a user deletes a message. It would still be returned on other devices because there would be no easy way of setting a certain deleted flag for group messages.
Does anyone know how apps like telegram, whatsapp and so on do this? And would method 2 give problems later on when millions of messages are sent?
Regards,
Ron
I would seperate it like this.
Messages
id, message, owner_id, deleted
Groups
id, name
Message_Group
message_id, group_id
User_Group
user_id, group_id
Then you can don't need to add a message to all users in that group. When you insert a new message you first inserts it into Messages, catch the id and inserts it into Message_Group with the message id and group id. To get the messages of a group just join Message_Group and Messages and you are pretty much done. Of course you also needs to join the user table to catch who wrote that messages.
Just like facebook, I have a website which shows lots of notifications from other users.
What I'm doing now is saving notifications of others if they are related to me with my user I'd and the actual user id of that notification in a table called notifications.
And when I login to dashboard I'm fetching all, for each notification I need to display user name so I'm making a query with each notification for the user using the id saved.
Its not efficient and a slow process when I get more notifications on dashboard.
I'm sure there is another tricky way..if I log into facebook it manages very quickly.
Any one had this situation? I'm sire every developer crossed this state, please help me if you have found any better ideas in solving this. So we query once for the associate user and bring the data in a single query.
For better performance you could retrieve the username by using a JOIN in your query when retrieving the notifications for a specific user e.g.
SELECT `message`, `username`
FROM `notifications`
INNER JOIN `users` ON `notifications`.`from_user` = `users`.`id`
I'm building a web application in work and I have a form where users can register certain types of information.
Username | Password | Company
Now I'm unsure how to approach this. What I want is when the user submits that registration form Username, password and company get written to one data table(user) BUT because Company, in the user data table, is a foreign key reference I need Company to be written to a separate datatable(company) as a Primary Key (and of course username to be written as a FK reference as its a 1 - 1 relationship).
I'm not looking for a coded solution from you guys because I know my PHP and MYSQL I'm just looking for some pseudo code algorithms to get the creative juices flowing!
EDIT: I AM USING POSTGRESQL not MYSQL but I'm pretty sure there's little difference except port numbers and small syntax changes
assume first column is id:
Save Company $mysqli->query("INSERT INTO company VALUES (NULL, '$company_name')";
Get id of this item. $company_id = $mysqli->insert_id;
Save User with this id $mysqli->query("INSERT INTO user VALUES (NULL, '$username', '$password', '$company_id')";
Get user's id $user_id = $mysqli->insert_id;
Update the company with it: $mysqli->query("UPDATE company SET user_id = $user_id WHERE company_id = $company_id)";
Begin to insert your compagny in your table compagny.
Get back the id. (There is a sql requete like LastInsertId)
Insert the user/password/IdCompagny in your table user.
EDIT : some help : http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Some questions:
why is User:Company == 1:1? If I and a coworker join your site, do we need to pretend to work at different places?
if companies can have more than one employee, what kind of validation will you employ to combine variations on company names (e.g. IBM vs International Business Machines)?
what if a user is unemployed?
If Company is a nice-to-know datum rather than a required-or-things-break datum, I'd probably sign up my user first. Then, when the user logs in you can nag them for additional information. This has the added advantage of making user registration less onerous for the user.
A use case:
user submits username and password
filtre input for bad stuff and validate for duplication, suitability
save to db and retrieve user PK
load 'additional info' page and set a session var as a "nag" flag
-if user chooses not to fill out add'l info, nag flag can trigger reminder behaviour
add autocomplete to Company field so that user can use existing Company table entries
process form and save to db
either add company and associate user
or just associate user
unset session nag flag so your website won't continue to nag
I have have created a Private messaging system using PHP and mySQL with notification a bit like Facebook.
The database table has following fields( not all listed):
MessageID
senderUserID
RecUserID
Message
Subject
DateTime
Status - whether read or not
RepliedStatus - how should i use this?
DeleteRec - delete from inbox
DelSender - delete sender inbox
RepliedUserId - When user reply to orginal message this is change to receiver's id
All replies are stored in a second table, since each message create a thread. The second table looks a bit like this:
messageID - FK
repuserID
Mesage
DateTime
At the moment when a new message is sent out to a user i change the 'status' of the message to unread, From this can run a count query to list all of the unread messages in notification.
But if the users replies back to that message i cant set the original 'status' field to unread, since this will appear on both users notification. so i created another field called 'RepliedStatus ' but i am unsure how would i use this to show notification on message reply?
thanks guys.
If you have a replies table then you don't need a replied status column on your first status. By virtue of there existing a record in the replies table you know that a user has replied to a message
Why dont you add an INT and nullable column to the first table (let's say, "messages" table) named "previous_message"?
ALTER TABLE messages ADD COLUMN previous_message INT DEFAULT NULL;
So every message will have in the same table the previous one, and you can work out the sequence. If it helps you can have a "next_message" column with same definition and update the relevant record on reply.
Doing so you can use the status column on each reply.
If you want to keep the same DB organisation I would suggest to add a column status on the second table (let's say "replies").
Hope this helps
Me I'll put deleted column once and the same things for the read or not-read like:
[{"0":"both", "1":"Sender", "2":"receiver"}];
And then fetching a tread messaging like:
$sql = "SELECT * FROM messagetreads
WHERE (senderID OR receiverID = ".$_SESSION['MyCurrentId'].")
AND deleted !== 0
ORDER by TreadID AND DateTime ASC";
When a sender "delete" is tread... All tread relatedID in the database change for 1 or 0 if delete colomn is 2...
But I think it's better to creat another colomn for getting of the repeated deleted and notifications data like
TreadID (FK_message_Table)
delete (0=both deleted UserID=don't appear to this sender or receiver)
notify (0=both read UserID=read to this sender or receiver)
Then it's ezee to change a status or a delete statement.
The SELECT will be sometings like this:
$SQL = "SELECT *
FROM messagetreads
WHERE (senderID OR receiverID = ".$_SESSION['MyCurrentId'].")
IN (SELECT TreadID WHERE delete !== (0 OR ".$_SESSION['MyCurrentId']."))";
If is our member id involve in the colomn delete all the tread don't appear but if is the id of the receiver when the sender will delete 0 can be attributed so that both of the members can "delete" the message. Same thing for notifications!
very far later a cron-job can come delete very-old message read(0)...
PS: this can be notification system too like notifying for a new post in wall or comment on a photos or new events on calendar ... just add more information in column data and faormat it with php or java-ajaxed alike...
I would like to make it able for my users to add each other as friends. I just don't know exactly how to do it.
I have a table called "members" where the users have (ofc) and ID,username,pass etc etc. and then I was thinking of creating another table called "friends", where I was planning to have the rows -> username (the friend added) and friend_to (who the friend 'belongs' to).
But; I just don't know - how I should make the "add friend" link, and make it INSERT INTO the table? Can I make an onClick on the link, or what should I do? :-s
Thanks in advance.
Have a table called friends have rows, (id, user_id, friend_id, status, time)
id is the index, user_id is the one requesting friendship, friend_id is the receiver, status is the status of friendship like pending or declined, and time is the timestamp of the time when the request was sent.
Then in a php code check if the users aren't friends then let them add each other as friends. One way you could check was like this
(SELECT COUNT(*) AS total WHERE (`user_id` = ".$_SESSION['user_id']." AND `friend_id` = ".$_GET['friend_id'].") OR (`user_id` = ".$_GET['friend_id']." AND `friend_id` = ".$_SESSION['user_id']."))
the above code will check if they are users, and if they are you would not let them re add each other, if they aren't the user gets a button to add them to friends, where it inserts into a database new row, with user_id being the user sending and friend_id the user's page the sender is submitting the button from
On the backend, you will need separate PHP functionality (easiest way is to simply have a separate PHP page) to handle the result of the "add friend" link. Your table layout seems adequate from what you have describe. The "Add Friend" link will need to send a request back to the add_friend PHP handler which includes ID of the user and the ID of the user they added. And this handler will be where you include the MySQL code for performing the insert, based on the data that is provided to it.
On the front end, you can have the link send them to a new page, or you can use an onclick event to issue an AJAX request and update things behind the scenes without requiring a page reload. That choice is up to you and what fits your design best. The later is more complicated and will require some Javascript and/or jQuery to handle the AJAX parts, but it often results in a more pleasant user experience.