PHP 表自动更新客户端



我正在尝试让一个网站每 (x( 秒使用最新数据自动更新客户端的表,这些数据存储在数据库中并不断接收更新。目前,查看最新数据的唯一方法是在网站上执行 Ctrl+F5 刷新。

任何帮助将不胜感激,代码如下:

include ('./vam_index_header.php');
include ('./helpers/conversions.php');
header('Cache-Control: no-cache');
header('Pragma: no-cache');
if (!isset($_GET["page"]) || trim($_GET["page"]) == "") {
?>
<?php
$sql = 'select callsign, arrival, departure, flight_status, name, surname, pending_nm, plane_type from vam_live_flights vf, gvausers gu where gu.gvauser_id = vf.gvauser_id ';
if (!$result = $db->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
}
$row_cnt = $result->num_rows;
$sql = "SELECT flight_id FROM `vam_live_flights` WHERE UNIX_TIMESTAMP (now())-UNIX_TIMESTAMP (last_update)>180";
if (!$result = $db->query($sql)) {
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $result->fetch_assoc())
{
$sql_inner = "delete from vam_live_acars where flight_id='".$row["flight_id"]."'";
if (!$result_acars = $db->query($sql_inner))
{
die('There was an error running the query [' . $db->error . ']');
}
$sql_inner = "delete from vam_live_flights where flight_id='".$row["flight_id"]."'";
if (!$result_acars = $db->query($sql_inner))
{
die('There was an error running the query [' . $db->error . ']');
}
}
if ($row_cnt>0){
?>
<div class="row" id="live_flights">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><IMG src="images/icons/ic_flight_takeoff_white_18dp_1x.png">&nbsp;<?php echo "LIVE FIGHTS" ?></h3>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-hover" id="live_flights_table">
<?php
echo "<tr><th>" . LF_CALLSIG . "</th><th>" . LF_PILOT . "</th><th>" . LF_DEPARTURE . "</th><th>" . LF_ARRIVAL . "</th><th>" . FLIGHT_STAGE . "</th><th>". BOOK_ROUTE_ARICRAFT_TYPE . "</th><th>" . PERC_DONE ."</th><th>" . PENDING_NM . "</th></tr>";
?>
</table>
<?php include ('./vam_live_flights_map.php') ?>
</div>
</div>
</div>
</div>```

在您的情况下,最好的可能是使用EventSource.https://developer.mozilla.org/en-US/docs/Web/API/EventSource 通过一些示例很好地描述了它。

EventSource 实例打开与 HTTP 服务器的持久连接,该服务器以文本/事件流格式发送事件。

还有一个例子 https://www.w3schools.com/html/html5_serversentevents.asp

我已经在后端代码在一个循环中运行的场景中使用了那里,该循环每个循环休眠几秒钟。并且循环的每次迭代都可以检测是否有新数据可用,它会发送一些相应的事件消息,这些消息可以被前端收集。

另一个很好的例子可以在 https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

我有一句话要告诫。使用while(true){}样式循环时,如果客户端连接已关闭,则必须创建一种中断循环的方法。当您可以执行以下操作时...

<?php
while(true) {
//... some code
// A way to break out of the loop.
if (connection_aborted()) {
break;
}
}

最新更新