如何通过JQuery/Ajax请求返回最新的Mysql条目


How to return latest Mysql entry through JQuery/Ajax request

我正试图通过ajax提取mysql表的最新条目,并将其显示为div中的html内容。我有ajax和php功能正常,唯一的问题是我想查询新条目并在循环中按时间间隔堆叠结果,我遇到了两个问题:让数据表现得像正常的javascript字符串,以及使循环只返回唯一的条目。

update.php文件

$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] =   $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);

JQuery Ajax请求循环:

$(document).ready(function(e){
  var comment;
  function commentLoop() {
    comment = $('#testdiv').load('update.php');
    $('#testdiv').append(comment);
    setTimeout(commentLoop, 6000);
  }
  commentLoop();
  $(document).focus();
});

问题是,通过执行SELECT * FROM conversations,您一直在请求整个表——尽管您只获取最后一个表。

您的代码需要记住已加载的注释,并且只获取比该注释更新的注释。

例如,假设主键是增量的,则执行SELECT * FROM conversations WHERE convid > ?。用已加载的最新注释替换?。如果你是第一次加载,只需执行SELECT * FROM conversations

您可以将使用请求参数显示的最后一个注释id传递到update.php中。此外,我建议以JSON格式返回数据,这样您就可以返回注释和id的集合,并轻松解析

这将对表中的注释进行计数,并选择最后输入的注释,然后将它们作为json数据传递给ajax,仅当接收到的计数低于表中注释的计数时:

PHP:

if(isset($_GET['data']))
{   
    $con        = new mysqli('host', 'user', 'password', 'database');
    $init_count = $_GET['data'];
    $stmt1      = "SELECT COUNT(*) AS count FROM conversations";
    $stmt2      = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
    $total = $con->prepare($stmt1);
    $total->execute();
    $total->bind_result($count);
    $total->fetch();
    $total->close();    
    if( ($init_count != '') && ($init_count < $count) )
    {
        $lastComment = $con->prepare($stmt2);
        $lastComment->execute();
        $result = $lastComment->get_result();
        $row    = $result->fetch_assoc();
        $lastComment->close();
        $data = array(
                 'comment' => $row['comment'],
                 'count'   => $count
                 );
    }
    elseif($init_count == '')
    {
        $data = array(
        'comment' => '',
        'count'   => $count
        );
    }
    $pdo->close();
    echo json_encode($data);
}

HTML:

<input type="hidden" id="count" value="" />

JQUERY:

$(document).ready(function(e){
    function getComment(){
        var count = $('#test').val();
        $.ajax({
                type: 'get',
                url: 'update.php?data=' + count,
                dataType: 'json',
                success: function(data)
            {
            $('#count').val(data.count);
            if(data.comment) !=  $('#testdiv').html(data.comment);
            }
        });
    }
    getComment();
    setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10

insert_date插入日期-时间注释,我希望您将有一个用于存储的字段,如果现在不添加它,