Alanay Alanay - 12 days ago 7
MySQL Question

How To Make PHP SQL SELECT Statements Query Every 5 Seconds?

I know how to set an interval for a function, and tried using it in this case but I could not get it to work. Here is my code. I need it to make the same SELECT statement every 5 seconds.

$Select = "SELECT * FROM Messages ORDER BY ID DESC LIMIT 10";
$Result = $Connect->query($Select);

if (mysqli_num_rows($Result) > 0) {
while($Row = mysqli_fetch_assoc($Result)) {
echo "ID " . $Row["ID"] . " MSG " . $Row["Message"] . "<BR>";
}
}

Answer

This can be done using PHP's sleep(). I really would not suggest this as it does not behave like JS setInterval(). PHP is not asynchronous like JS.

<?php
    function setInterval($func, $seconds) {
        while(TRUE) {
            $func();
            sleep($seconds);
        }
    }

    setInterval(function() {
        global $Connect;
        $Select = "SELECT * FROM `Messages` ORDER BY `ID` DESC LIMIT 10";
        $Result = $Connect->query($Select);

        if(mysqli_num_rows($Result) > 0) {
            while($Row = mysqli_fetch_assoc($Result)) {
                echo 'ID ' . $Row['ID'] . ' MSG ' . $Row['Message'] . '<br>';
            }
        }
    }, 5);
?>

Your best bet would be to use AJAX to load this into the window using the JS setInterval() method, assuming you want this displayed in HTML since you are using <br/> tags.