Zuckerberg Zuckerberg - 1 month ago 6
MySQL Question

Why MYSQL loop is freezing the client browser?

I have php script that runs for sometime while waiting for the data from the MySQL database.
The problem is that when the client refreshes the browser, this does not seem to work, instead, it keeps waiting...

code below with loop

<?php
session_start();//i start the session here.
require_once('connections/connections.php');//mysql


function loop_to_get_more_data(){
global $con;


//checking number of connected friends in db...
$check=$con->query("SELECT numfriends FROM SUPERDATATABLE WHERE USERID=$_SESSION[USERID] AND numfriends>0");
if(mysqli_num_rows($check)>0){

//here i do more work and finally exit;

}else{
//loop again...
sleep(3);
loop_to_get_more_data();
return;//required to stop.
}

}loop_to_get_more_data();


exit;//after finshing everything...


Now as u can see, the code works perfectly but the problem is that
this loop FORCES the browser to wait untill the server responds to the request or exits the loop when data is there

When the client refreshes the browser, the browser refuses to refresh itself and it keeps the same status no matter what.

what am i doing wrong here.?

Answer

I think you are looking for the session_write_close(); function

<?php
session_start();//please make note of this.
require_once('connections/connections.php');

//NOW CLOSE THE SESSION RIGHT BEFORE ENTERING THIS FUNCTION LOOP
session_write_close();//this does the magic.

function loop_to_get_more_data(){
    global $con;

    $check=$con->query("SELECT numfriends FROM SUPERDATATABLE WHERE USERID=$_SESSION[USERID] AND numfriends>0");
    if(mysqli_num_rows($check)>0){
        //more code if any;
    }else{
        sleep(3);
        loop_to_get_more_data();
        return;//required to stop.
    }

}loop_to_get_more_data();

exit;
Comments