Php 在基本长轮询示例上实现MySQL

Php 在基本长轮询示例上实现MySQL,php,mysql,Php,Mysql,我试图创建一个测试应用程序,在将新数据插入数据库后检索消息,这是一个基本的“长轮询”,我遵循并使用了其中的文件,但是这个脚本只从名为“data.txt”的文件中获取数据,我如何使用相同的逻辑,在插入新数据后立即从数据库中获取数据 以下是php代码: set_time_limit(0); // where does the data come from ? In real world this would be a SQL query or something $data_source_file

我试图创建一个测试应用程序,在将新数据插入数据库后检索消息,这是一个基本的“长轮询”,我遵循并使用了其中的文件,但是这个脚本只从名为“data.txt”的文件中获取数据,我如何使用相同的逻辑,在插入新数据后立即从数据库中获取数据

以下是php代码:

set_time_limit(0);

// where does the data come from ? In real world this would be a SQL query or something
$data_source_file = 'data.txt';

// main loop
while (true) {

    // if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
    $last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;

    // PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
    clearstatcache();
    // get timestamp of when file has been changed the last time
    $last_change_in_data_file = filemtime($data_source_file);

    // if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
    if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {

        // get content of data.txt
        $data = file_get_contents($data_source_file);

        // put data.txt's content and timestamp of last data.txt change into array
        $result = array(
            'data_from_file' => $data,
            'timestamp' => $last_change_in_data_file
        );

        // encode to JSON, render the result (for AJAX)
        $json = json_encode($result);
        echo $json;

        // leave this loop step
        break;

    } else {
        // wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
        sleep( 1 );
        continue;
    }
}
jquery代码:client.js

function getContent(timestamp)
{
    var queryString = {'timestamp' : timestamp};
    $.ajax(
        {
            type: 'GET',
            url: 'http://127.0.0.1/long_polling/server/server.php',
            data: queryString,
            success: function(data){
                // put result data into "obj"
                var obj = jQuery.parseJSON(data);
                // put the data_from_file into #response
                $('#response').html(obj.data_from_file);
                // call the function again, this time with the timestamp we just got from server.php
                getContent(obj.timestamp);
            }
        }
    );
}

// initialize jQuery
$(function() {
    getContent();
});

php错误日志和javascript控制台中出现了哪些错误?(F12)这样想:一个文件只不过是一系列记录(行),而一个数据库是相同的。对于数据库,有两种方法。示例一:如果当前表有10条记录(行),您所要做的就是通过计数记录来检查是否插入了新记录,如果有11条记录,则有新数据。例二:如果一条记录被更新了,那么就有不同的数据。我没有得到任何错误,脚本运行得很好,我只是不知道如何把数据库放在上面;