聊天室信息发送者和接收者之间的不同背景颜色不起作用

时间:2016-05-19 14:01:37

标签: php

我想要做的是让邮件在发件人和收件人之间具有不同的背景色

这是我的代码

<?php 

  include '../config.php';
  include'login.php';

  $username = $_SESSION['username'];

  $msg = $_REQUEST['msg'];

  $sql = mysqli_query($connection,"INSERT INTO logs(`username`, `msg`)VALUES('$username', '$msg')");
  $sql1= "SELECT * FROM logs ORDER by id ASC ";

  $result1 = mysqli_query($connection,$sql1);

  if ($_SESSION['username'] == $username)
    $color = 'red';
  else
    $color = 'purple';

  while($extract = mysqli_fetch_array($result1)){

  echo "
  <div class='left-wrap-message' style='background-color:$color;'>
    <span class = 'username'>". $extract['username']. 
    "</span><span class='msg'> : "  . $extract['msg']. "</span></div><br>";
    }

?>

这是用于加载消息的日志文件

<?php 
  include '../config.php';
  include'login.php';

  $username = $_SESSION['username'];

  $sql1= "SELECT * FROM logs ORDER by id ASC";

  $result1 = mysqli_query($connection,$sql1);


 if ($_SESSION['username'] == $username)
    $color = 'red';
 else
    $color = 'purple';


 while($extract = mysqli_fetch_array($result1)){

 echo "<div class='left-wrap-message' style='background-color:$color;'>
 <span  class = 'username'>". $extract['username']. "</span>
 <span  class='msg'> : " . $extract['msg']. "</span></div><br>";
 }

&GT;

我搞砸了什么?我知道为什么它不会工作

2 个答案:

答案 0 :(得分:2)

您需要将$ username与循环中的提取用户名进行比较,这应该有效:

<强> PHP

  <?php 

  include '../config.php';
  include'login.php';

  $username = $_SESSION['username'];
  $msg = $_REQUEST['msg'];

  $sql = mysqli_query($connection,"INSERT INTO logs(`username`, `msg`)VALUES('$username', '$msg')");
  $sql1= "SELECT * FROM logs ORDER by id ASC ";

  $result1 = mysqli_query($connection,$sql1);

  while($extract = mysqli_fetch_array($result1)){
  $color = ($extract['username'] == $username) ? 'red' : 'purple';
  $position = ($extract['username'] == $username) ? 'left' : 'right';
  echo "
  <div class='" . $position . "-wrap-message' style='background-color:$color;'>
    <span class = 'username'>". $extract['username']. 
    "</span><span class='msg'> : "  . $extract['msg']. "</span></div><br>";
    }

?>

答案 1 :(得分:1)

嗯,您正在设置$username = $_SESSION['username'];,所以当它到达您的if / else语句时,它总是会被解析为真。

您需要将if / else放在while内,并将行用户名与$ username进行比较。