I have a notifications system (PHP, MySQL- based) and I am trying to do the following: Query notifications results grouped by posts without any limit but then ordered by time_sent limited to 5 (per iteration). Then I used an ajax to show the next iteration set of 5 notifications.
Basically I need 5 notifications at a time (per set) but for each of them, if a group concerns one post: there can be as many notifications as wanted:
This is how there will be displayed:
- Notification concerning post F – sent 1 day ago
- First notification concerning post C – sent 2 days ago
- Second notification concerning post C – sent 3 days ago
- Third notification concerning post C – sent 4 days ago
- Fourth notification concerning post C – sent 5 days ago
- Notification concerning post Y – sent 3 days ago
- First notification concerning post D – sent 4 days ago
- Second notification concerning post D – sent 5 days ago
- Third notification concerning post D – sent 6 days ago
- Notification concerning post Y – sent 5 days ago
If a new notification were sent concerning post Y, this would be upped to the top of the list naturally.
This is how I had started, before I decided to implement this group system:
$notifications_req = mysql_query('SELECT * FROM notifications WHERE user_id = "'.$user_id.'" ORDER BY time_sent DESC LIMIT 5');
And now I got lost, and struggle with this group by and order by logic.
The database contains of course a post_id
column.
EDIT:
I ended up changing quite drastically the way I wanted to sor the notifications. This is how I eventually did it. It might not be the most efficient, but it works the way I want:
<?php $notifications_all_req = mysql_query('SELECT * FROM notifications WHERE user_id = "'.$user_id.'" ORDER BY time_sent DESC'); if(mysql_num_rows($notifications_all_req) > 0){
while($row = mysql_fetch_assoc($notifications_all_req))
{
$post_req_ids[] = $row['post_id'];
}
$unique_post_ids = array_unique($post_req_ids);
foreach ($unique_post_ids as $i => $unique_post_id)
{
?>
<ul id="notifications_ul_<?php echo $i; ?>">
<?php
$notifications_req = mysql_query('SELECT * FROM notifications WHERE (user_id = "'.$user_id.'" AND post_id = "'.$unique_post_id.'") ORDER BY time_sent DESC ');
while($notification = mysql_fetch_assoc($notifications_req))
{
}
?>
</ul>
<?php
} } ?>
This way, I can control the limits of both the notifications group (using $i
) and the ones within each group, also with an Ajax load more code for the latter.