PHP中的Php自动刷新数据

时间:2017-12-26 10:38:08

标签: php

我想在php中提问。我想制定一个计划并改变它的价值观。 我放了一个图像,然后在上面放了一些数据。我想刷新自动这个值。

<div class="container">
  <img src="ahol.PNG" alt="Norway" style="width:100%;">
  <div class="data1">$data1 kWh </div>
 <div class="data2">$data2 kWh </div>
   <div class="data3">$data3 kWh </div>
 <div class="data4">$data4 kWh </div>
</div>

这是我在同一个文件中获取数据的PHP代码;

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

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

$sql = "SELECT * FROM makinebilgi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {    
        $data1 =$row["data1"];
        $data2= $row["data2"];
        $data3= $row["data3"];
        $data4= $row["data4"];
    }
} else {
    echo "0 results";
}
$conn->close();

此页面我想使用能源系统手表。我每秒都会向数据库添加能量值。我想仅自动刷新数据而不是页面。

2 个答案:

答案 0 :(得分:2)

您可以使用ajax实现此目的。

制作data.php文件并输入您的后端代码:

<?php

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

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

$sql = "SELECT * FROM makinebilgi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $data1 =$row["data1"];
        $data2= $row["data2"];
        $data3= $row["data3"];
        $data4= $row["data4"];
        echo "<img src='ahol.PNG' alt='Norway' style='width:100%;'>";
        echo "<div class='data1'>" . $data1  . "</div>";
        echo "<div class='data2'>" . $data2  . "</div>";
        echo "<div class='data3'>" . $data3  . "</div>";
        echo "<div class='data4'>" . $data4  . "</div>";
    }
} else {
    echo "0 results";
}
$conn->close();


?>

更新客户端:

   <div class="container" id="output"></div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

从客户端进行ajax调用:

<script>
    $(document).ready(function(){
        function getData(){
            $.ajax({
                type: 'POST',
                url: 'data.php',
                success: function(data){
                    $('#output').html(data);
                }
            });
        }
        getData();
        setInterval(function () {
            getData(); 
        }, 1000);  // it will refresh your data every 1 sec

    });
</script>

答案 1 :(得分:1)

当您需要在不重新加载页面的情况下不断从数据库中获取数据时,有几个选项可用 - ajaxwebsocketsServer Sent Events可能是最常用的选项。

由于您的c#应用程序正在更新数据库,您不需要websockets提供的完整双向功能,也不需要查询数据库需要不断发送参数,以便我可以选择这些可能的选项是SSE只是因为它很容易设置,并且不需要持续的乒乓流量(请求/响应)

一个非常简单的Server Sent Events脚本,每n秒查询一次数据库,并将记录集作为有效负载发送到javascript客户端。

<?php

    /* sse.php */

    set_time_limit( 0 );
    ini_set('auto_detect_line_endings', 1);
    ini_set('max_execution_time', '0');
    ob_end_clean();

    /*-------------------------------------------------------------------------*/
    $refresh=!empty( $_GET['refresh'] ) ? intval( $_GET['refresh'] ) : 1;
    $evtname=!empty( $_GET['evtname'] ) ? $_GET['evtname'] : 'sse';
    /*-------------------------------------------------------------------------*/


    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $db  = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

    /* get last record ~ assumed `id` column being auto-increment */
    $sql='select * from `makinebilgi` order by `id` desc limit 1;';


    function sse( $evtname='sse', $data=null, $retry=1000 ){
        if( !is_null( $data ) ){
            echo "event:".$evtname."\r\n";
            echo "retry:".$retry."\r\n";
            echo "data:" . json_encode( $data, JSON_FORCE_OBJECT | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS );
            echo "\r\n\r\n";
        }
    }

    header('Content-Type: text/event-stream'); 
    header('Cache-Control: no-cache');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET');
    header('Access-Control-Expose-Headers: X-Events');


    while( true ){
        if( connection_status() != CONNECTION_NORMAL or connection_aborted() ) break;

        $payload=array();
        $result = $db->query( $sql );
        while( $rs=$result->fetch_object() ){
            $payload[]=$rs;
        }


        /* send the payload */
        call_user_func( 'sse', $evtname, $payload );


        /* -- Send output -- */
        if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @flush();


        /* wait for defined period before repeating loop */
        sleep( $refresh );

    } //end infinite loop


    if( @ob_get_level() > 0 ) {
        for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
        @ob_end_clean();
    }
?>

使用一些简单的javascript来调用Server Sent Events脚本

的客户端代码
<?php

?>
<!doctype html>
<html>
    <head>
        <title>sse display of data from c# app to db</title>
        <script>
            (function(){
                var options={capture:false,once:false,passive:false};

                document.addEventListener('DOMContentLoaded',function(event){

                    var url='/path/to/sse.php?refresh=1&evtname=sse';

                    var d1=document.getElementById('d1');
                    var d2=document.getElementById('d2');
                    var d3=document.getElementById('d3');
                    var d4=document.getElementById('d4');

                    if ( !!window.EventSource ) {

                        var evtSource = new EventSource( url );
                        evtSource.addEventListener( 'sse',function(e){
                            var json=JSON.parse( e.data );
                            var keys=Object.keys( json );
                            var obj=json[ keys[0] ];

                            console.info( json,keys );

                            d1.innerHTML=obj.data1;
                            d2.innerHTML=obj.data2;
                            d3.innerHTML=obj.data3;
                            d4.innerHTML=obj.data4;

                        },options );
                    }
                },options );
            })();
        </script>
    </head>
    <body>
        <div class='container'>
            <img src='ahol.PNG' alt='Norway' style='width:100%;'>
            <div id='d1' class='data1'></div>
            <div id='d2' class='data2'></div>
            <div id='d3' class='data3'></div>
            <div id='d4' class='data4'></div>
        </div>
    </body>
</html>

以上都没有经过测试但是应该没问题 - 虽然我的宿醉状态永远不会知道。