I'm creating a system and I want it to bring all the results already stored in the database, but it only returns the recorded data from the moment I refresh the page, for example if I enter 10 records in the database, the 10 will appear the moment I'm on the page, but when I update, everyone is gone!
In the database I have a table named longpolling
and the columns id
, notificacao
( varchar(200)
), and timestamp
(of type timestamp).
Long Polling PHP script:
<?php
$timestart = time();
$pdo = new PDO('mysql:host=localhost;dbname=longpolling', 'root', '');
if(isset($_POST['timestamp'])){
$timestamp = $_POST['timestamp'];
}else{
$pega_time = $pdo->prepare("SELECT NOW() as now");
$pega_time->execute();
$row = $pega_time->fetchObject();
$timestamp = $row->now;
}
$sql = $pdo->prepare("SELECT * FROM notificacoes WHERE timestamp > '$timestamp'");
$newData = false;
$notificacoes = array();
while(!$newData && (time()-$timestart)<20){
$sql->execute();
while($row = $sql->fetchAll(PDO::FETCH_ASSOC)){
$notificacoes = $row;
$newData = true;
}
usleep(500000);
}
$pega_time = $pdo->prepare("SELECT NOW() as now");
$pega_time->execute();
$row = $pega_time->fetchObject();
$timestamp = $row->now;
$data = array('notificacoes' => $notificacoes, 'timestamp' => $timestamp);
echo json_encode($data);
exit;
Jquery Script:
<script type="text/javascript">
$(function(){
pegaNotificacoes();
});
function pegaNotificacoes(timestamp){
var data = {};
if(typeof timestamp != 'undefined') {
data.timestamp = timestamp;
}
$.post('longpolling.php', data, function(res){
for(i in res.notificacoes){
$('#resultados').append(res.notificacoes[i].notificacao+'<br>')
}
pegaNotificacoes(res.timestamp);
}, 'json');
}