Junc Book
Junc Book

Reputation: 21

How to show comments notification in php

I have three tables "posts", "comments" and "friend_request"

screenshot Database Structure

1: If someone comments on SESSION['id'], the notification must appear.

Existing query for "posts"

SELECT * FROM posts WHERE post_user = '".$_SESSION['id']."'

post_id = postId;
post_user = postUser;

comments on posts

SELECT * FROM comments WHERE post_id = '$post_id' AND user_id != '".$_SESSION['id']."' AND status = '0'"

I want if someone comments on my post, and I reply to the comments, I just want to show notifications on the commentator's sidebar only, even if there will more replies.

friend_request is a table where displaying either member are friends or not.

Upvotes: 1

Views: 454

Answers (1)

rattybag
rattybag

Reputation: 421

The way I would approach this is to use a client side AJAX request to a php fetch script that looks at the logged in users SESSION['id'] to find all comments made by post authors that are children of a comment the logged in user has made

Frontend

You may use whatever way you want to send a request to your PHP script, I have used jQuery for simplicity.

The jQuery $.ajax function will be ran on the page continuously to check for notifications. This has been done by enclosing it in a setInterval function.

This code is not tested so not 100% sure on the namespacing of the PHP array you will get back. Best to console.log the data object in the success handler here.

You will notice that there is reference to a readComment.php script, this can be a simple script that sets the comments.status = 1 to indicate read status.


  setInterval(function() {
    $.ajax({
   url:"fetch.php",
   method:"GET",
   success:function(data)
   {
    console.log(data)
    data.forEach(function(i,v) {
        $( "#notifications" ).append( "<a href=readComment.php?id=" + v.id + ">unread notification</p>" );
    });

   }
  });
 }
}, 60 * 1000); // This will run every minute to check for notifications

Server

fetch.php

I am using a select statement here with two WHERE IN clauses to retrieve all comments made by post authors that are children of a comment the logged in user has made. I am not 100% on this query either as I have not tested but this should get you started.

$query = "SELECT 
    *
FROM
    comments
WHERE
    comments.user_id IN (SELECT posts.post_user FROM posts)
AND
    comments.parent_comment_id IN (SELECT comments.id FROM comments WHERE comments.user_id = ".SESSION['id'].")"
AND 
    comments.status = 0";

$result = mysqli_query($connection, $query);

header("Status: 200");
header('Content-Type: application/json');
echo json_encode(array('data' => mysqli_fetch_array($result) )); 
die;

Let me know if you need more information.

Upvotes: 1

Related Questions