PHP:如何在 MySQL 中显示与其他行不同的特定行?

标签 php mysql css chat livechat

我正在创建一个 php 聊天应用程序,我有这个聊天的两个面板,一个是管理区域,另一个是客户聊天区域,两个面板区域的内容显示在一个名为 messages 的表中只想以不同于客户端用户的颜色显示管理内容或名称。

如何做到这一点?有什么想法吗?

这是我的 display_messages.php

中的代码
session_start();
require_once 'cn.php';
require_once 'protect.php';



$fiveMinutesAgo = time() - 1000;

$sql = "SELECT * FROM messages ORDER BY message_time  ";
$result = mysqli_query($cn,$sql) or
    die(mysqli_error($cn));



while ($row = mysqli_fetch_assoc($result)) {
    $user = $row['username'];
    $msg_content = $row['message_content'];
    $hoursAndMinutes = $row['message_time'];

    echo '<p><cite class="fa fa-user"><b>'. $user .':</b></cite> <output>'. $msg_content .'</output> <time class="fa fa-clock-o time">: ' . $hoursAndMinutes . ':</time></p>';

}

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

假设您在 messages 表中有一个名为 role 的列,它可以是“admin”或“user”,那么您的循环可能如下所示:

while ($row = mysqli_fetch_assoc($result)) {
    $user = $row['username'];
    $msg_content = $row['message_content'];
    $hoursAndMinutes = $row['message_time'];
    $class = $row['role'];

    echo '<p class="'.$class.'">'.
            '<cite class="fa fa-user">'.
              '<b>'. $user .':</b>'.
            '</cite>'.
            '<output>'. $msg_content .'</output>'.
            '<time class="fa fa-clock-o time">: ' . $hoursAndMinutes . ':</time>'.
           '</p>';

}

你可以添加

.admin{color:red}
.user{color:black}

到你的CSS

虽然这是一个广泛的例子。你真的应该加入用户表上的消息表

编辑

将您的查询更改为:

 $sql = "SELECT m.*,u.role FROM messages m ".
        "JOIN users u on u.username = m.username ORDER BY message_time";

并使用

在您的用户表中添加一列
  "ALTER TABLE `users` ADD `role` VARCHAR(5);"

在你的 sql 客户端中。

但是如果您有多个同名用户,这将不会很好地工作,消息表应该有一个用户 ID 列,而不是用户名列,您应该加入该列。

关于PHP:如何在 MySQL 中显示与其他行不同的特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844354/

相关文章:

javascript - 如何使提交按钮成为 href 和图像

php - 通过 PHP 获取具有重复键的 JSON 数据

php - 如何验证 PayPal 返回数据?

mysql - 两列作为mysql中的主键?

ios - 转换不适用于 IOS

php - 在while循环中查询,我怎样才能提高这个速度?两种数据库类型

如果在组中找到 NULL 值,Mysql 会排除组

php - Cakephp 2 : need help on misconfiguration with PDOStatement

javascript - jQuery:根据索引分配类

javascript - Ace Editor 在 <head> 标签内生成 CSS 样式