我已经设置了一个数据库和一个小网站。在网站上,我应该能够看到数据库中的所有数据,并显示新条目。为此,我已经包含了" setInterval();"。 setinterval每秒都会启动应该读取数据库的函数。我没有得到任何错误,第一次该函数实际读取整个数据库,但它只是每秒写入相同的东西,没有任何来自数据库的新输入。每次我的函数被称为数据库中的所有内容(包括所有新条目)时,我怎么能做到这一点。
var t= "";
setInterval(checkDb, 1000);
function checkDb(){
<?php
session_start();
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "RFID";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT `id`, `rfid`, `dateandtime` FROM`scans`';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$answer= "id: " . $row["id"]. " - RFID: " . $row["rfid"]. " - Date:" . $row["dateandtime"]. "<br>";
?>
t= <?php echo json_encode($answer);?> + t ;
document.getElementById("myP").innerHTML = t;
<?php
}
} else {
echo "<br>" ."\n0 results\n";
}
$conn->close();
session_destroy();?>
t="";
};
答案 0 :(得分:0)
您可以在第一次打开页面时使用jquery load加载php脚本,然后在x秒加载脚本后使用setInterval
<script type="text/javascript">
$('document').ready(function(){
$('#myP').load('php-script.php');//load the script immediately
setInterval(function(){setUpdates()}, 10000);
});
function setUpdates(){
$('#myP').load('php-script.php');
}
</script>
<强> PHP-的script.php 强>
<?php
session_start();
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "RFID";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT `id`, `rfid`, `dateandtime` FROM`scans`';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$answer = "id: " . $row["id"] . " - RFID: " . $row["rfid"] . " - Date:" . $row["dateandtime"] . "<br>";
}
} else {
echo "<br>" . "\n0 results\n";
}
$conn->close();
session_destroy(); // I dont think u need this
?>