我正在尝试使用 PHP 和 MySQL 在网页上显示实时数据。
到目前为止,我能够从数据库中检索记录并每 3 秒显示一次。然而,相同的记录每 3 秒显示一次,直到插入新记录(即存在重复记录)。
我认为我需要在 while
循环中进行更多检查?
我无法检查唯一的TimeStamp
,因为会有多个记录具有相同的时间戳,这是完全有效的。
SerialNo
字段是主要的、唯一的,并且在每次插入后递增 1 - 也许我可以以某种方式使用它?
我的PHP;
$query = "SELECT TimeStamp, CardNo, SerialNo FROM transactions WHERE TimeStamp < ? ORDER BY TimeStamp DESC LIMIT 1";
$time = date('Y-m-d H:i:s');
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $time);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$cardNo = $row['CardNo'];
echo "retry: 3000\n\n"; // every 3 seconds
echo "data: ".$cardNo. ' '.$row['TimeStamp']. "\n\n"; // card no & timestamp
}
我的 HTML;
<script type="text/javascript">
window.onload = function(){
var source = new EventSource("data.php");
source.onmessage = function(event){
document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
};
};
</script>
HTML 页面上的数据输出示例(如您所见,输出了重复项);
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 02723884 2017-08-10 10:54:39
New transaction: 02723884 2017-08-10 10:54:39
New transaction: 02723884 2017-08-10 10:54:39
New transaction: 02723419 2017-08-10 10:54:49
New transaction: 02723419 2017-08-10 10:54:49
New transaction: 02723419 2017-08-10 10:54:49
New transaction: 02723419 2017-08-10 10:54:49
New transaction: 02730552 2017-08-10 10:55:01
New transaction: 02730552 2017-08-10 10:55:01
我希望它看起来像这样(没有重复);
New transaction: 12916064 2017-08-10 10:52:03
New transaction: 02723884 2017-08-10 10:54:39
New transaction: 02723419 2017-08-10 10:54:49
New transaction: 02730552 2017-08-10 10:55:01
感谢任何帮助。
最佳答案
你想要做的是(在 PHP 中):
如果 session 中的 SerialNo(即这应该代表发送到客户端的最后一个 SerialNo)与 $row 中的 SerialNo 相同,则不要将数据发送到客户端。
否则,如果它们不相同,则将数据发送到客户端,并将新的 SerialNo 存储在 session 中代替旧的 SerialNo。
类似这样的事情:
session_start(); //at the top of the script, ideally.
//...then, after your query, when you've fetched the row:
if ($_SESSION["lastSerialNo"] != $row["SerialNo"])
{
$_SESSION["lastSerialNo"] = $row["SerialNo"]; //store new "last" serial no in the session
//...send data to client as you do now
}
else
{
//probably don't need to do anything here, just don't send the data.
}
关于javascript - 没有重复的服务器端事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45610414/