首页 > 解决方案 > 使用 PHP 刷新/更新从 mySQL 加载的数据表中的数据

问题描述

所以我终于设法填充数据表,但由于 mySQL 中一直有一些更新,我正在寻找从 mySQL 刷新/重新加载最新数据的方法。

到目前为止,我在data.php中有这个

    <?php
    include "connect.php";
    $sqlAdmin = mysqli_query($connection, "SELECT FROM_UNIXTIME(lastChange) as new_date,pair, percentage, delta_t, current_price, last_price FROM testdatabase.table ORDER BY id DESC LIMIT 0,100;");    
    $locations = array();
    while($res = mysqli_fetch_array($sqlAdmin)) {
        $locations[] = array($res['new_date'], $res['pair'], $res['percentage'], $res['delta_t'], $res['current_price'],$res['last_price']);
  }
?>

并且数据表在index.php中(只有重要内容的较短版本)

<!-- TABLE -->
<table id="example" class="display compact myTableClass">
    <thead>
        <tr>
        <th scope="col">Date</th>
        <th scope="col">Pairing</th>
        <th scope="col">Percentage</th>
        <th scope="col">Delta time</th>
        <th scope="col">Current price</th>
        <th scope="col">Past Price</th>
        </tr>
    </thead>
    <tbody id="myTable" class="dark-theme-table">
    </tbody>
</table>
           
<!-- LOAD DATA FROM MYSQL -->
<?php   include "data.php";  ?>
          
<script>
    // load data from php to variable
    var mydata  = <?php echo json_encode($locations); ?>;

    console.log(mydata);
        
    // this should reload new data every 5 seconds 
    var refreshId = setInterval(function()
    {
        <?php  include "data.php"; ?>
        mydata  = <?php echo json_encode($locations); ?>;
        console.log('Refresh ... ',mydata)
    }, 5000);

    var table = $('#example').DataTable({
        data: mydata
        // a lot of additional options, not important to show
        });
        
    $(document).ready(function() {
      table.draw();
    });
      
</script>

我的主要问题是如果我这样做,刷新的数据不是最新的......我正在控制台中检查是否加载了新数据但到目前为止没有成功

有人知道如何解决这个问题吗?我应该以不同的方式处理这个问题吗?我应该将整个数据表放入新的 .php 并刷新它吗?

问候

标签: javascriptphphtmlmysqldatatable

解决方案


推荐阅读