Long Polling with mysqli does not return data

Asked

Viewed 408 times

4

The data of data php. file database does not return, if I change the whole data php. for any html text it returns running long Polling, but if I try to use mysqli it returns nothing.

What can I do to fix this problem ?

It is not SELECT error because if you open the data php. separate it returns the data.

index php.

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <script type="text/javascript" src="client.js"></script>
    </head>
    <body>
        <h3>Conteúdo</h3>
        <div id="response"></div>

    </body>
</html>

php server.

<?php
// arquivo cujo conteúdo será enviado ao cliente
$dataFileName = 'data.php';
while ( true )
{
    $requestedTimestamp = isset ( $_GET [ 'timestamp' ] ) ? (int)$_GET [ 'timestamp' ] : null;

    // o PHP faz cache de operações "stat" do filesystem. Por isso, devemos limpar esse cache
    clearstatcache();
    $modifiedAt = filemtime( $dataFileName );

    if ( $requestedTimestamp == null || $modifiedAt > $requestedTimestamp )
    {
        $data = file_get_contents( $dataFileName );

        $arrData = array(
            'content' => $data,
            'timestamp' => $modifiedAt
        );

        $json = json_encode( $arrData );

        echo $json;

        break;
    }
    else
    {
        sleep( 2 );
        continue;
    }
}
?>

client js.

function getContent( timestamp )
{
    var queryString = { 'timestamp' : timestamp };

    $.get ( 'server.php' , queryString , function ( data )
    {
        var obj = jQuery.parseJSON( data );
        $( '#response' ).html( obj.content );

        // reconecta ao receber uma resposta do servidor
        getContent( obj.timestamp );
    });
}

$( document ).ready ( function ()
{
    getContent();
});

data php.

<?php
$conexao = mysqli_connect ("localhost","usuario","senha","db");
$resulta = mysqli_query ($conexao,"SELECT * FROM nome");
while ($exibe = mysqli_fetch_array($resulta)){
?>

<?php echo $exibe['nomes']; ?>

<?php } ?>
  • Does a javascript error appear in the browser console? in data.php avoid using the php closing tag. related

  • @rray The Code is all ok working perfectly, it seems that long Polling does not update php code only texts, if you test using some text in the date.php vera that works very well long Polling, but if using a mysql or php function no longer takes.

2 answers

2


The problem is in file_get_contents() of your code.

When you use the file_get_contents() in a php file (the way it was used in your code), it will return to code string; ie, it will not be processed as php.

What would make the code be interpreted as expected would be the function include, but I don’t know if that would apply.

I see you’re trying to verify the modification date of the file, but this would be inefficient, since you would have to check a date in the bank (since the query is in the bank); and, at no time, there is in your script changing the date of the file (through some modification).

I’ve used a script very similar to this to study Long Polling, and your script looks a lot like the one I used. I can assure you that it will not work for operations with the MYSQL.

The only way to make it work (not one of the best), is to exchange

that:

$dataFileName = 'data.php'

therefore:

$dataFileName = 'http://localhost/sua_pasta_de_testes/data.php';

Thus, you would be actually picking up an HTML response from your already executed PHP script, and not it just as a file in a folder. Because file_get_contents works both for files in your directory and for urls (if the directive allow_url_fopen your PHP.ini is set to On).

  • Got it, thank you I’m studying long Polling and ta hard... if you say that this system will not work for mysql I think I’ll go to another. even altering does not come result, but it would not suit me.

  • If you’ve found something better in your studies and can pass me thanks.

  • I think the @Beraldo answer will be able to help you a lot. I haven’t tried it, but the logic seems to be correct.

2

This example was I who posted on my blog. There are times many ask me how to adapt the example to use database. See how to do using PDO and Sqlite:

$dbFile = 'comments.db';

$PDO = new PDO( "sqlite:" . $dbFile );

while ( true )
{
    $requestedTimestamp = isset ( $_GET [ 'timestamp' ] ) ? (int)$_GET [ 'timestamp' ] : time();

    $stmt = $PDO->prepare( "SELECT author, comment, timestamp FROM comments WHERE timestamp >= :requestedTimestamp" );

    $stmt->bindParam( ':requestedTimestamp', $requestedTimestamp );
    $stmt->execute();

    $rows = $stmt->fetchAll( PDO::FETCH_ASSOC );

    if ( count( $rows ) > 0 )
    {
        $json = json_encode( $rows );

        echo $json;
        break;
    }
    else
    {
        sleep( 2 );
        continue;
    }
}

If you prefer to use Mysqli instead of PDO, just change the script a little by modifying the PDO class by Mysqli. But the logic is the same.

I updated the original post with the example using PDO and Sqlite. See it here: http://rberaldo.com.br/server-push-long-polling-php-ios/

  • 1+. But, if you are already using the fetchAll, why then give a foreach to reallocate the same data to another array? just give a json_encode($rows)

  • 1

    @Wallace-maxters indeed, nor need the foreach. It was force of habit. I will edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.