如何从每两个用户的对话中获取最新消息

时间:2019-12-05 19:28:40

标签: php session mysqli

我正在创建消息对话脚本,我想从每两个用户的对话中获取最新消息。我的脚本显示所有from_id消息。任何人都可以帮助我,我已经尝试了很多。

我的数据库pm表结构

id  from_id    to_id     msg               sent_date
1   2          3         hi how are you?   2019-12-05 04:14:20
2   3          2         fine              2019-12-05 05:15:58
3   2          3         hi                2019-12-05 03:20:34
4   5          2         hi                2019-12-05 08:30:40

这是我的源代码

<?php
require_once "config.php";
if (isset($_SESSION['userid'])) {
    $to_id = $_SESSION['userid'];
}
if ($stmt = $con->prepare("SELECT * from pm where to_id=? or from_id=?  ")) {
    $stmt->bind_param('ss', $to_id, $from_id);
    $stmt->execute();
}
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        ?>

<?php echo $row['msg']; ?>

<?php
    }
} else {
    echo "NO MESSAGES";
}

?>

1 个答案:

答案 0 :(得分:1)

我想出了这个解决方案,对我来说很难在SQL查询中完成所有这些工作。这种解决方案实际上并不是最好的,但我能想到的最好。

$sessionId = <session id variable>;

if ($stmt = $con->prepare("SELECT * FROM pm WHERE from_id = ? OR to_id = ? ORDER BY sent_date DESC")) {
    $stmt->bind_param('ii', $sessionId, $sessionId);
    $stmt->execute();
}



$tempArray = array();

$result = $stmt->get_result();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {

      if (!in_array($row['to_id'].$row['from_id'], $tempArray)) {
        echo "<br>";
        echo $row['from_id']." - " . $row['to_id']." ". $row['msg']. " - " .$row['sent_date'];
      }

      array_push($tempArray, $row['from_id'].$row['to_id']);
      array_push($tempArray, $row['to_id'].$row['from_id']);


    }
} else {
    echo "NO MESSAGES";
}

每个对话中最后一条消息的图像:

image of every last message from every conversation