使用Ajax和PhP将数据从Postgresql数据库放到表中 [英] Put data from Postgresql database to table using Ajax and PhP

查看:48
本文介绍了使用Ajax和PhP将数据从Postgresql数据库放到表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是每5秒钟使用ajax和php从postgresql数据库中填充数据。我按照示例如何使用ajax和php将数据从数据库表放入html表。我是PhP的新手,所以我不知道为什么没有填充数据。我对代码进行了测试,并成功在控制台中获取了数据,但未在表中获取数据。
客户端代码

The goal of my task is to populate data from postgresql database every 5 seconds using ajax and php. I followed the example How to put data from database table to a html table using ajax and php. I am new in PhP so, I don't know why data is not populating. I did testing of the code and got data in console successfully but not in table. Client side code

<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/hardwarestatus.css'; ?> </style>
</head>
<body>
<div class="maindiv">
        <div id="tagsDiv"> 
                <h3>Estat Tags</h3>
                <?php  

                        echo '<table id="tags_table">';
                        echo "<tr>";
                                echo '<th>' . "TAG" . '</th>';
                                echo '<th>' . "BATTERY" . '</th>';
                                echo '<th>' . " Time " . '</th>';
                                echo '<th>' . "Status" . '</th>';
                        echo "</tr>";
                        echo '</table>';                            
                ?>
        </div>

</div>

<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>

<script>
$(document).ready(function(){
        UpdateHTMLTable();
        setInterval(function() {
                UpdateHTMLTable();
        }, 5000); // 5000 millisecond(5 second)

function UpdateHTMLTable(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {


            myObj = JSON.parse(this.responseText);


            for (i = 0; i < myObj.length; i++) {

                console.log(myObj[i]);

                var row = $("<tr />");
                    $("<td />").text(myObj[i].mac).appendTo(row);
                    $("<td />").text(myObj[i].battery).appendTo(row);
                    $("<td />").text(myObj[i].ts).appendTo(row);
                    $("<td />").text(myObj[i].ts).appendTo(row);
                    row.appendTo('#tags_table');     
                } 
        }
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
}
});
</script>

</body>
</html> 

在服务器端,我的代码是

<?php 
header("Content-Type: application/json; charset=UTF-8");  
        $host = ip of the host";
        $port ="port no."; 
        $user = "user"; 
        $pass = "123"; 
        $db = "db_name"; 
        $con = pg_connect("host=$host dbname=$db user=$user password=$pass")
        or die ("Could not connect to server\n"); 
        $query = "Query string"; 
        $result = pg_query($con, $query) or die("Cannot execute query: $query\n");
        if(pg_num_rows($result))
        {
            $data=array();
            while($row=pg_fetch_array($result))
            { 
                $data[] = array(
                'mac'=>$row['mac'],
                'ts' =>$row['ts'],
                'battery'=>$row['battery']
                 );
            }         
            echo  json_encode($data);
            pg_free_result($result);
            pg_close($con);
        }                                
?>


推荐答案

我没有测试过,但是方法是:

I didn't tested this one but the approach is :


  1. 从php生成表,并在每个 td元素上用id表示数据库中的标识符

  2. 在线设置 data 属性以标识哪一行已更改

  3. 从Web服务获取更新数据时,将其与您的jquery数据元素进行比较

  1. Generate the table from the php with id on each td element representing the identifier in database
  2. On line set data attribute to identify which line has changed
  3. When you get update data from your webservice you compare it to your jquery data elements

类似的东西

$(document).ready(function(){
    const tableEl = $('#tags_table');
    UpdateHTMLTable();
    setInterval(function() {
        UpdateHTMLTable();
    }, 5000); // 5000 millisecond(5 second)

    // An object returned by php reprensenting your data
    const rowHasChanged = function(obj) {
        const lineObj = $('tr#' + obj.id);
        if !(lineObj) {
            return false;
        }

        // Do your logic here
        if (lineObj.data('status') !== obj.status) {
            return true;
        }
        return false;
    };
    function UpdateHTMLTable(){
        const xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {   
            if (this.readyState == 4 && this.status == 200) {
                const data = JSON.parse(this.responseText);
                for (i = 0; i < data.length; i++) {
                    const myObj = data[i];
                    if(rowHasChanged(myObj)) {
                        // Do your stuff to colorize the line, or something to alert
                    }
                }    
            }
        };
        xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
        xmlhttp.send();
    }
});

别忘了添加所有相关数据和标识符,以便能够与您的Web服务更新进行比较

Don't forget to add all the related data and identifier to be able to compare with your webservice update

echo '<table id="tags_table">';
    echo "<tr>";
        echo '<th>' . "TAG" . '</th>';
        echo '<th>' . "BATTERY" . '</th>';
        echo '<th>' . " Time " . '</th>';
        echo '<th>' . "Status" . '</th>';
     echo "</tr>";
 echo '</table>';

这篇关于使用Ajax和PhP将数据从Postgresql数据库放到表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆