如何使用 PHP、AJAX、JQuery 自动从数据库获取最新数据(输入时)到我的网页?
我使用了以下代码,它工作正常。但我需要在数据库中输入新数据后立即在网页上获取并显示更新的数据。
<?php
$hostname = '127.0.0.1';
$username = 'xxxxxxxxxxx';
$password = 'xxxxxxxxxxx';
try {
$dbh = new PDO("mysql:host=$hostname;
dbname=sensor_measurements",
$username, $password);
/*** The SQL SELECT statement ***/
$sth = $dbh->prepare("
SELECT `dtg` AS date,
`temp` AS temperature,
`humid` As humidity,
`acous` As acoustic,
`accel_x` As accelx,
`accel_y` As accely,
`accel_z` As accelz
FROM `sensor_data`
ORDER BY date DESC
LIMIT 1
");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$json_data = json_encode($result);
echo $json_data;
?>
最佳答案
在js中保存最后获取到的数据的id,然后进行简单的比较。例如,在 php 中创建一个仅获取 id 的查询,如果 id 不同,则每 5 秒运行一次,然后获取您发布的 php 代码。
关于php - 如何自动从数据库中获取最新数据(输入时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994456/