使用AJAX监控数据库的变化PHP

时间:2012-12-29 04:47:42

标签: php mysql jquery

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

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

    <?
    $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); 
    }
    ?>

3 个答案:

答案 0 :(得分:1)

<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服务器的超时

建议的apache配置

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

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;
?>

答案 1 :(得分:0)

你的php代码中缺少一些分号。我觉得它根本不起作用。您应该检查回发脚本中生成的php错误消息。

在您的javascript中,您将结果与布尔值进行比较。返回的数据将是一个字符串。这是正确的方法,请注意单引号。

if(data.result=='true'){ 
window.location = window.location.pathname;
}

答案 2 :(得分:0)

checker.php

转换为JSON格式后发送数据
但是ajax请求中的 根本没有定义数据类型, 如果ajax成功的数据是JSON,那么你必须先解析它..

        $.ajax({
               type: "GET",
               url: 'checker.php',
               data:{'ata:$resultado},
               dataType:"json",
               success:function(data){
                       if( JSON.parseQuery(data)) //this will run if the result is true.
                         {
                          window.location = window.location.pathname;
                         }            
               }
           });