2017-11-11 35 views
0

我一直試圖抓取兩個用戶之間的聊天消息,並希望將它們放在兩個不同的div s中,並分別對兩個div進行樣式設置。我現在正在做的是獲取聊天記錄,並將其放入單獨的「消息」中,但我想要獲取數據,並希望將它放在「消息」div內的兩個div中。一次抓取數據並放入兩個不同的div

function fetch_chat() { 
    // to fetch the chats between two users 
    $.ajax({ 
     url: "fetch_chat.php", 
     method: "POST", 
     data: { 
      id: currentID 
     }, 
     dataType: "text", 
     success: function(data) { 
      $("#messages").show(); 
      $('#messages').html(data); 
      $("div.area").show(); 
      //chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time 
      if (!scrolled) { 
       $("#messages").animate({ scrollTop: $(document).height() }, "fast"); 
       scrolled = true; 
      } 
     } 
    }); 
} 

<?php 
require("config.php"); 
$id = $_POST['id']; 
$sql = "select * from users where id='$id'"; 
$res = mysqli_query($con, $sql); 
$row = mysqli_fetch_array($res); 
$user_to = $row['name']; 
$sql1 = "select * from chats where user_from='$_SESSION[name]' AND user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to' order by id"; 
$res1 = mysqli_query($con, $sql1); 
if (mysqli_num_rows($res1) > 0) { 
    while ($row = mysqli_fetch_array($res1)) { 
     echo $row['msg']; 
    } 
} else 
    echo "No msgs <br />"; 
?> 

回答

-1

從數據庫中獲取數據時,如果消息來自用戶,則給它一個類,否則給它一個不同的類。然後在顯示聊天結果的html文件中,定義這些類樣式。包括在其中具有的功能fetch_chat()文件中的這些款式,

 <style> 
     .mine { 
      background-color: lightblue; 
     } 

     .notMine { 
      background-color: lightyellow; 
     } 

    </style> 

,而PHP的將是

<?php 

    require("config.php"); 
    $id= $_POST['id']; 
    $sql="select * from users where id='$id'"; 
    $res=mysqli_query($con,$sql); 
    $row=mysqli_fetch_array($res); 
    $user_to= $row['name']; 
     $sql1="select * from chats where user_from='$_SESSION[name]' AND user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to' order by id"; 
     $res1=mysqli_query($con,$sql1); 
      if(mysqli_num_rows($res1)>0){ 
       while($row=mysqli_fetch_array($res1)){ 
        if($row["user_from"] === $_SESSION["name"]) { 
         echo "<div class='mine'> $row[msg] </div>\n"; 
        } 
        else { 
         echo "<div class='notMine'> $row[msg] </div>\n"; 
        } 
        //echo $row['msg']; 
       } 
      } 
     else { 
      echo "No msgs <br />";  
     } 
    ?> 
+0

但會話[名]誰是當前登錄的用戶名因此,if(userfrom == session(name))將始終爲真。我已經嘗試了這一點,並獲得了相同顏色的全部消息 –

+0

我們正在檢查每行 - 此行消息是由用戶發送還是由接收 - 如果($ row [「user_from」] === $ _SESSION [「name」]) - 所以如果這個特定的消息是由用戶發送的話,那麼它會有不同的背景 –

+0

Um米我覺得我有點困惑....在我的插入查詢我已經插入會話(名稱)時發送郵件。這就是爲什麼if語句將永遠是真實的在我的情況。你可以建議我如何插入發送它的用戶的名稱或ID ... –

相關問題