dongtan1009 2013-08-29 19:18
浏览 24

MYSQLi SELECT获取对象

    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();
    }

The code is the server for a long polling connection with client. If update is requested, the while loops check for any new messages received after the timestamp sent with the update request. If found, it puts the result in an array and echo it back to the client. The resulting output is something like this [msgs:[{msg_from:"",msg_to:"",msg:"",msg_datetime:""},{msg_from:"",msg_to:"",msg:"",msg_datetime:""}]]

The code works fine for the first time and send all the recent messages well encapsulated but then it again sends an empty array of messages. Please guide me.

  • 写回答

1条回答 默认 最新

  • dongwu9647 2013-08-29 21:11
    关注

    solved the issue with 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; }    
    

    thanks everyone for their help!

    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应