0
    if ( isset($_POST['update']) ){
    $db=mysqli_connect("localhost","****","****","****");
    $lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
    while (1){
        sleep(1);
        clearstatcache();
        $mresult = mysqli_query($db,"SELECT * FROM tblchat WHERE msg_datetime > $lasttime");
        if (!empty($mresult)){ break; }
    }
    $msgs = array();
    while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; }
    mysqli_free_result($mresult);
    $response = array();
    $response['msgs'] = $msgs;
    echo json_encode($response);
    flush();
    mysqli_close($db);
    exit();
    }

该代码是用于与客户端进行长轮询连接的服务器。如果请求更新,while 循环会检查在随更新请求发送的时间戳之后收到的任何新消息。如果找到,它将结果放入一个数组并将其回显给客户端。结果输出是这样的[msgs:[{msg_from:"",msg_to:"",msg:"",msg_datetime:""},{msg_from:"",msg_to:"",msg:"",msg_datetime:""}]]

该代码第一次工作正常,并发送所有最近的消息,封装得很好,但随后它再次发送一个空的消息数组。请指导我。

4

1 回答 1

0

解决了mysqli_num_rows的问题

if (mysqli_num_rows($mresult)){ $msgs = array(); while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; } mysqli_free_result($mresult); break; }
if (mysqli_num_rows($wresult)){ $writers = array(); while ($row = mysqli_fetch_object( $wresult )) { $writers[] = $row; } mysqli_free_result($wresult); break; }    

感谢大家的帮助!

于 2013-08-29T21:11:51.457 回答