I am using PHP and MySQL to build a personal message system. The 'New-Message'-Counter needs to display the number of unread messages for each conversation. I am using a MySQL function to check the number of unread messages and a JQuery function to update the counter.
The problem is that the 'New-Message'-Counter is not working correctly. The expected output is to display the number of unread messages for each conversation. However, the variable countMessages
doesn't contain the actual message count (as it is supposed to).
The SQL query to get the message count:
function check_unread_messages($chat_id, $from_id) {
return (mysql_result(mysql_query("SELECT COUNT(*) FROM `messages` WHERE `group_id` = $chat_id AND `from_id` = $from_id AND `read_on` is NULL"), 0));
}
jQuery-Function where I call the SQL-query and try to update the div displaying the number of unread messages:
jQuery(document).ready(function() {
jQuery(setInterval(function() {
friends_count = document.getElementsByClassName("user").length;
for(var i=1; i < friends_count+1; i++) {
el = document.getElementById(i);
conv_id = el.getAttribute("data-user-id");
user_id = el.getAttribute("data-conv-id");
my_user_id = "<?php echo $session_user_id; ?>";
cache = "check_unread_messages("+conv_id+", "+user_id+")";
countMessages = "<?php "+cache+" ?>";
if(countMessages > 99) {
countMessages = "99+";
}
if(countMessages > 0 || countMessages == "99+") {
document.getElementById("badge-"+i).innerHTML = countMessages;
}
}
}, 500));
});
And this is the Container for the Counter:
<div class="user" id='<?php echo $i ?>' data-user-id='<?php echo $user_id?>' data-conv-id='<?php echo $conversation['id'] ?>'>
// something, that doesn't matter
<?php // normaly php gets opend in "something, that doesn't matter"
echo "<div class='rightCountUnreadMessages'>";
echo '<div class="badge" id="badge-'.$i.'"></div>';
echo "</div>";
?>
</div>
In the jQuery Function user_id
and conv_id
are correct as far as I can tell. I guess, that there is something wrong with the 2 lines after that (cache = ...
)