gpt4 book ai didi

php - 一次获取数据并放入两个不同的 div

转载 作者:行者123 更新时间:2023-11-28 15:13:22 25 4
gpt4 key购买 nike

我一直在尝试获取两个用户之间的聊天消息,并希望将它们放在两个不同的 div 中,并分别设置两个 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 />";
?>

最佳答案

从数据库中获取数据时,如果消息来自用户,则给它一个类,否则给它一个不同的类。然后在显示聊天结果的 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 />";
}
?>

关于php - 一次获取数据并放入两个不同的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47233877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com