PHP的聊天重复用户防止

时间:2018-09-02 09:44:02

标签: php

我有问题,在我的代码上我创建了聊天,但是用户名重复,我尝试阻止但未成功。...有些可以帮助吗?

我的代码:

    $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 picture

我不想重复用户。

1 个答案:

答案 0 :(得分:0)

您可以将过滤后的收件箱条目与要显示的数据一起保存在一个数组中,但是仅当用户不在该数组中时才可以。这样,它仅添加一次。之后,您可以通过普通的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
}