php - MYSQLi SELECT Fetch Object

445
    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.

566

Answer

Solution:

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!

People are also looking for solutions to the problem: php - Divide the string into parts and convert it to an array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.