使用AJAX&监控数据库上的更改的PHP [英] Monitor changes on database with AJAX & PHP

查看:59
本文介绍了使用AJAX&监控数据库上的更改的PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一种监视器,该监视器显示由另一个Web应用程序创建的数据库更改,我每10秒重新加载一次页面以显示更改,但是,我认为这不是要做的事情"它,所以我进行了一些研究,发现ajax可以做到这一点,调用一个检查更改的函数,所以我编写了代码,但是缺少了一些东西,因此打电话给专家,主要思想是当页面进入加载后插入最后一行的id(number),然后将其保存在名为$ resultado的变量中,然后调用一个名为check_changes的函数,该函数执行相同的查询并检查结果,如果两个变量相等,则没有变化,如果它们不同,则重新加载页面.

i am making a kind of monitor, that shows the changes on database that are created by another web application, i was reloading the page every 10 seconds to show the changes but, i think that is not the "way" to do it, so i was made some research and i found that ajax can do that, calling a function that check that changes, so i wrote my code, but something is missing, so am calling the experts, tha main idea is that when the page are loaded take the id(number) of that last row that was inserted and then saved in a variable called $resultado then call a function called check_changes that do the same query and check the results, if the both variable are equal then no changes, if they are different the reload page.

monitor.php

monitor.php

    <head>
    <script type="text/javascript" src="./js/prototype.js"></script>
    <script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script>
    </head>

    <?
    //code that makes and print the query.

    // here i check the last id(number) and saved on $resultado variable
    $qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
    $qry1=db_query($qry0,$conn);
    while($row=$qry1->fetch_array()) 
    { 
    $resultado=$row['id'];
    }

    //here i call check_changes every 30 seconds
    echo "<script>setTimeout('check_changes()',30);"; 
    //ajax function that check the status of database
    echo "function check_changes(){
    $.ajax({
type: 'POST',
data: {'data':$resultado}, //here am sending the value of result via post
url: './checker.php',   //to checker.php
success: function(data) {
if(data.result==true){ 
window.location = window.location.pathname;
} 
}
})
    }";
    echo "</script>";
    ?>

checker.php

checker.php

    <?
    $result4 = $_POST['data'];
    include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
    $dbc=connect_db("seguridad");

    // here i check the last id(number) and saved on $result3 variable
    $qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
    $qry1=$dbc->query($qry0);
    while($row=$qry1->fetch_array()) 
    {  
    $result3=$row['id'];
    }

    //here i check if both are equal send false to monitor.php
    if ($result4==$result3){
    $result=false
    echo json_encode($result); 
    }
    else {
    // a new row has been inserted, send true to monitor.php an reload page
    $result=true
    echo json_encode($result); 
    }
    ?>

推荐答案

<script type="text/javascript">
var pollTimeout;
var observeChange = {
          'poll' : function() {
              $.ajax({
                   type: "POST",
                   url: 'checker.php',
                   data:"data=<?php echo $resultado; ?>",
                   dataType:"json",
                   async:true,
                   success:function(response){
                        // we have success fully received response,clear the timeout
                       clearTimeout(pollTimeout);                                          
                       observeChange.update(response);                             
                   },
                   error: function(XMLHttpRequest,textStatus){
                        //some error has occured please try after 5 seconds
                        pollTimeout = setTimeout(function()
                        {
                            observeChange.poll();
                        }, 1000);

                    }
                });

          },
          'update' : function(json) {
              //check whether change is there from serever or not if yes than reload page else do poll request again
              if(json.changed=="yes"){
                        window.location.reload();
              }
              else{
                observeChange.poll();
               }
          }
    };
    $(document).ready(function(){
      observeChange.poll();           
    });
    </script>

您可以轻松地通过彗星完成此操作,建议不要每10秒查询一次服务器,如果使用apache,则应增加apache服务器上的超时时间

you can easily do it via comet,it is not advisable to query server for every 10 seconds,you should increase timeout on apache server if you are using apache

建议的apache配置为

suggested apache configurations are

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 240
MaxClients 150
MaxRequestsPerChild 4

checker.php

checker.php

<?
$result4 = $_POST['data'];
$response=array("changed"=>"no");
include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
$dbc=connect_db("seguridad");

// here i check the last id(number) and saved on $result3 variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=$dbc->query($qry0);
while($row=$qry1->fetch_array()) 
{  
$result3=$row['id'];
}

if ($result4==$result3){
   $response['changed']="yes"; 
}
echo json_encode($response); exit;
?>

这篇关于使用AJAX&amp;监控数据库上的更改的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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