Long Polling with mysqli does not return data

4

The data from the database's .php file does not return, if I change the whole data.php to any html text it returns working the long polling , but if I try to use mysqli it does not return anything.

What can I do to correct this problem?

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

index.php

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

    </body>
</html>

server.php

<?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 } ?>
    
asked by anonymous 09.01.2015 / 00:29

2 answers

2

The problem is in file_get_contents() of your code.

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

What would make the code interpreted as expected would be the include function, but I do not know if that would apply.

I see that you are trying to verify the modification date of the file, but that would be inefficient, since you would have to check a date in the database (since the query is in the database); and at no time in your script does the file date change (by any modification).

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

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

this:

$dataFileName = 'data.php'

so:

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

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

    
10.01.2015 / 18:34
2

This example was the one I posted on my blog. Many times I have been asked how to adapt the example to use the database. Here's how to do it 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 bit 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: link

    
11.01.2015 / 20:21