php chat duplicate users prevent
php chat duplicate users prevent
i have problem, on my code i create chat, but duplicate users name, i try prevent but not success.... some can help?
my code:
$sql = "SELECT * FROM `inbox` WHERE `from`='".$_SESSION['username']."' OR `to`='".$_SESSION['username']."' ORDER by `data` DESC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$lastuser = "";
while($row = mysqli_fetch_array($result))
$chat_name = "";
if($row['from'] == $_SESSION['username'])
$chat_name = $row['to'];
else
$chat_name = $row['from'];
if($lastuser != $chat_name)
echo "
<a href='?user=".$chat_name."'>
<div class='inbox_users_box'>
<div class='inbox_imagenuser'>
<img class='inbox_image' src='".getAvatarOthers($chat_name)."'></img>
<div style='margin-top: 14px; float: left;'>".$chat_name."</div><span style='margin-top: 17px; margin-left: 5px;' class='".getonline_player($chat_name)."'></span>
<div style='clear:both;'></div>
</div>
<div class='inbox_lastmsgdata'>".$row['data']."</div>
</div>
<div style='clear:both;'></div>
</a>
";
$lastuser = $chat_name;
my chat : my chat picture
i want dont duplicate users..
my full code as here,,, the problem are there and i dont know why..
– x3G
Sep 2 at 11:26
1 Answer
1
You can save the filtered inbox entries in an array with the data to display, but only when the user isn't already in that array. This way it gets added only once. After that you print the array the way you like with a normal foreach()
loop.
foreach()
$users = array();
while ($row = mysqli_fetch_assoc($result);
// retrieve the data from MySQL
$chat_name = "";
if($row['from'] == $_SESSION['username'])
$chat_name = $row['to'];
else
$chat_name = $row['from'];
$data = $row['data'];
// look if the user is already in the array
$found = false;
foreach ($users as $user)
if ($user['name'] == $chat_name)
$found = true;
break;
if ($found)
continue;
// its not, so add it
$toAdd = array('name' => $chat_name, 'data' => $data);
$users = $toAdd;
}
/* display users */
foreach ($users as $user)
$username = $user['name'];
$data = $user['data'];
// your HTML code here
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please edit your question to include: 1. The full source code you have (see stackoverflow.com/help/mcve), 2. the current output you get and 3. the output you want to get.
– Progman
Sep 2 at 10:54