Automatically updating DIV contents from a Mysql table - one at a time

I need to automatically update the contents from the mysql data table every 5 seconds, but showing only one single record at a time, going through each record in an infinite loop.

I load news.php which has this js:

<script type="text/javascript">
var auto_refresh = setInterval(function () {
    $('#canvas').load('content.php').fadein("medium");}, 5000);
     // refresh every 5 seconds
</script>

content.php has a db connection

$query_Recordset5 = "SELECT * FROM news"; 
$Recordset5 = mysql_query($query_Recordset5, $connection) or die(mysql_error());
$row_Recordset5 = mysql_fetch_assoc($Recordset5);
$totalRows_Recordset5 = mysql_num_rows($Recordset5);

Like the fields selected on the page.

I understand that you will have to create a counter and return one other record each time, but I find it difficult to deal with it.

thanks

+4
source share
1 answer

(, "id" ). page.php id 0, , 0, jquery. , , , .

num_rows == 0 , - , , , , , , sql auto increment value.

<?php
// page.php
$id = (int) $_REQUEST['id'];
$sq = "select * from news where id > ".$id." order by id asc limit 0,1";
$qu = $con->query($sq);

if ($qu->num_rows == 0) {
    $sq2 = "select * from news order by id asc limit 0,1";
    $qu2 = $con->query($s2);
    while ($fe = $qu->fetch_assoc()) {
       echo $fe['id']."|".$fe['content'];
    }
} else {
    while ($fe = $qu->fetch_assoc()) {
       echo $fe['id']."|".$fe['content'];
    }
}
?>

<script>
$(document).ready(function() {
    setInterval(function(){ updateNews(); }, 5000);
});
function updateNews() {
    var id = 0;
    id = $("#hidden-id").val();        

    $.get("page.php?id=" + id, function(data) {
       // I use $.get so that I can split the data that it returns before populating 
       // the #canvas. This way we can strip off the first part which is the auto 
       // increment
       var ref = data.split('|');
       $("#hidden-id").val(ref[0]);
       $("#canvas").html(ref[1]);
    });
}
</script>
+1

Source: https://habr.com/ru/post/1616777/


All Articles