使用php对mysql运行常量查询,而无需刷新HTML页面

时间:2019-02-19 10:00:28

标签: php mysql ajax

我正在查看将mysql查询结果输出到php页面上的一个表中,其中表的第一列是结果,第二列填充有Javascript计时器

但是我的目标是拥有它,以便当数据进入mysql数据库时显示在表上,然后在查询停止拾取数据时将其从表中删除

但是,我面临的问题是我不确定在每次运行查询时如何在不重置JavaScript计时器的情况下执行此操作,

我经历了几个提到使用ajax的问题​​,这很好,但是我不确定我会把HTML放在哪一面

编辑: 下面是我现在使用ajax进行的第二次尝试代码,但是我无法获得表将其显示为意外令牌<第27行

我当前的页面加载代码以调用数据如下:

PHP

<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
#   header('Content-Type: applicaton/json');

$sql = "SELECT 
* 
FROM
(SELECT
  beacon,location,
  COUNT(location) AS counter 
FROM `track`
WHERE `date` = CURDATE() and `time` > NOW() - interval 60 second
GROUP BY beacon) AS SubQueryTable
ORDER BY beacon + 0 ASC;";
$result = $conn->query($sql);


$result = mysqli_query($conn ,  $sql);
   $rows = array();
   while($r = mysqli_fetch_assoc($result)) {
  $rows[] = $r;
    }

   echo json_encode($rows);
    $conn->close();
?>   

HTML             

    $.get('vendor/fetch.php', function(response) {
        console.log(response);
        var row;
        response.forEach(function(item, index) {
            console.log(item);

(unexpexted token here) 
<table id="table">
    <?php
    while($row = mysqli_fetch_array($result))
    {
    ?>
    <tr style="background-color: <?php echo $row['item.location'];?>">
    <td><?php echo $row['item.beacon'];?></td>
    <td> <span class='minutes'>00</span>:<span class='seconds'>00</span> 
    </td>
    </tr>

    <?php } 

    mysqli_close($con);  
    ?>
    </table>
        });
    });


        function updateTable() {
        //console.log('function called');
        $.get('vendor/fetch.php', function(response) {
            response.forEach(function(item, index) {
                console.log(item.beacon);

            });
        });

    var updateTableInterval = setInterval(updateTable, 100);
    };
</script>

 </head>

 <body>
<script>
var sec = 0;

function pad(val) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval(function () {
$(".seconds").html(pad(++sec % 60));
$(".minutes").html(pad(parseInt(sec / 60, 10)));
}, 1000);
</script> 
</body>

0 个答案:

没有答案