The*_*eek 5 javascript php mysql html5
我正在使用PHP和MySQL构建一个(非常基础的)应用程序.此应用程序的目的是在网页上显示"实时"数据事务.这些事务来自transactions
MySQL数据库中的表.
到目前为止,我可以在网页上检索和显示数据.但是,我希望只有在将新事务插入transactions
表中时才会看到数据刷新?
目前,实时馈送重复显示最后一条记录,直到插入新事务为止.
到目前为止我的代码是;
transactions.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML5 Server-Sent Events</title>
<script type="text/javascript">
window.onload = function(){
var source = new EventSource("transactions.php");
source.onmessage = function(event){
document.getElementById("result").innerHTML += "New transaction: " + event.data + "<br>";
};
};
</script>
</head>
<body>
<div id="result">
<!--Server response will be inserted here-->
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
transactions.php
<?php
include 'conn.php'; // database connection
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$query = "SELECT TimeStamp, CardNo FROM transactions ORDER BY TimeStamp DESC LIMIT 1";
// `TimeStamp` is in the format YYYY-MM-DD H:i:s
if ($result = $conn->query($query)) {
$row = $result->fetch_assoc();
echo "data: " . $row['CardNo'] . "\n\n";
}
flush();
?>
Run Code Online (Sandbox Code Playgroud)
如果这有任何不同,我一直在关注本教程.
我的问题;
任何帮助表示赞赏.
为了使这项工作正常进行,您在服务器端缺少一些东西。
首先,正如 @RiggsFilly 指出的,您需要在语句中使用 WHERE 子句。条件应该是寻找比上次发送的交易更新的交易。
为此,您需要跟踪上次发送消息的时间戳。
仅当带有条件的查询返回结果时,服务器才应发送消息。
最后,检查新交易并在发现时发送消息的整个例程必须保持在循环中。
<?php
include 'conn.php'; // database connection
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$query = "SELECT TimeStamp, CardNo FROM transactions WHERE TimeStamp > ?";
$stmt = $conn->prepare($query);
$ts = time();
while(true)
{
if ($result = $stmt->execute([$ts])) {
$row = $result->fetch_assoc();
echo "data: " . $row['CardNo'] . "\n\n";
$ts = $row['TimeStamp'];
flush();
}
sleep(2);
}
Run Code Online (Sandbox Code Playgroud)