Why I get duplicated data every time, although a php load only the logged in users
Look my code snippet here
Fetch the online members with:
$onlinemember = $db -> prepare(
"SELECT members.member_id, members.member_name, members.photo
FROM members
INNER JOIN members_details ON members.member_id = members_details.member_id
WHERE members_details.last_activity > DATE_SUB(NOW(), INTERVAL 5 SECOND) ");
$onlinemember -> execute();
The foreach statemement:
$result = $onlinemember -> fetchAll();
$mydata = array();
foreach($result as $data) {
$loopdata = array(
'member_name' => ucfirst($data['member_name']),
'photo' => ($data['avatar'] === "" ? 'default.png': $data['avatar']),
'you' => (($_SESSION['member_id'] === $data['member_id']) ? '(you)' : '')
);
array_push($mydata, $loopdata);
}
echo json_encode($mydata);
look my client side with jquery ajax to get all members and append them on the specific <div>
var fetch_user_online = "fetch_user_online";
$.ajax({
url:"fetch_user_online.php",
method:"POST",
data:{fetch_user_online:fetch_user_online},
dataType: 'json',
cache: false,
success:function(response) {
for(var i=0; i < response.length; i ) {
$('#online_status').append(response[i].member_name " " response[i].photo " " response[i].you);
}
}
Now the JQuery give out duplicate of online members, when I add .empty() it show only one member although the response from PHP return all members who are online.
$('#online_status').empty().append(response[i].member_name " " response[i].photo " " response[i].you);
remember I have the following query which update the login detail table, after every 3 sec from the set time interval in a JQuery Ajax snippet.
$update = $db -> prepare("UPDATE login_details
SET last_activity = ?
WHERE login_details_id = ?");
$update -> execute([date("Y-m-d H:i:s"), $_SESSION["login_id"]]);
CodePudding user response:
You need to empty the data once, before you start the loop, otherwise each time you look at the next record in the for loop it will remove the previous one you inserted only a moment earlier.
e.g.
success: function(response) {
$('#online_status').empty();
for(var i = 0; i < response.length; i ) {
$('#online_status').append(response[i].member_name " " response[i].photo " " response[i].you);
}
}
