drn1008 2012-04-18 04:59
浏览 77

如何检查mysql上是否有新数据

I need to write a application that checks database from external server every 10 seconds to see if there is new data. Currently I have a javascript that checks if data has changed server by comparing two JSON (the old JSON and the new fetched from server) and if it has alerts user. But that is not what I need in this application. User should be alerted only when data is new, not when it has changed.

I was thinking that maybe I could do this with a PHP code that queries MYSQL and if query num_results is 0 loop until num_results is more than 0 when user gets notified. In this application it doesn't matter whether the new data is available for user in 0,1 second or 10 seconds, just as long as user gets it. This is how I tried to do the MYSQL check, but it isn't working:

<?php
include 'config.php';

if(isset($_GET['ID'])) {
    $maxLoop = 20;    
    while($maxLoop--) {
        $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        try {
            $sth = $dbh->prepare('select * from testit where id = :id');
            $sth->bindParam(':id',$_GET['ID'],PDO::PARAM_INT);
            $sth->execute();
            if($sth->rowCount()>0) {
                $results = $sth->fetchAll(PDO::FETCH_OBJ);
                echo '{"key":'. json_encode($results) .'}';
                exit; // Found new data, end loop and script
            }
        } catch(PDOException $e) {
            break;   
        }
        sleep(3);    
    } // end while
} // end if

So how can I alter this code to make it work, or should I just try to write some javascript that would do this? And if so, how can I check whether data is new or not, instead of just checking whether it has changed or not?

  • 写回答

2条回答 默认 最新

  • dqrl3595 2012-04-18 05:03
    关注

    How do you record 'new' data? is there a timestamp? an auto_increment primary key field?

    The easiest method for polling is to simply keep track of the last known id/timestamp and see if there's anything with a higher id/newer timestamp.

    As is, your method is quite inefficient. You select ALL records in the table, forcing mysql/pdo to start fetching that data from disk, etc... then simply throw it away after getting the row count. A more efficient method is do to a select count(*) ... and checking that value. This keeps mysql from having to start fetching actual row data from disk. And on some table types (myisam in particular), a count(*) operation is VERY quick.

    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致